package com.example.shiwu;

import static com.example.shiwu.util.ArrayUtil.stringToDouble;
import static com.example.shiwu.util.ContextVariable.DOWN_NAME;
//import static com.example.shiwu.util.DataParseUtil.dataNormaliza;
import static com.example.shiwu.util.DataParseUtil.getKVal;
import static com.example.shiwu.util.SocketMergeCallBackUtils.convertUsingLoop;
import static com.example.shiwu.util.SocketMergeUtils.pauseThread;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.db.model.Alarm;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.ReceiveVolEle;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.model.User;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.manager.DynamicLineChartManager;
import com.example.shiwu.service.AlarmService;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.BoxEightService;
import com.example.shiwu.service.BoxFiveService;
import com.example.shiwu.service.BoxFourService;
import com.example.shiwu.service.BoxNineService;
import com.example.shiwu.service.BoxOneService;
import com.example.shiwu.service.BoxSevenService;
import com.example.shiwu.service.BoxSixService;
import com.example.shiwu.service.BoxTenService;
import com.example.shiwu.service.BoxThreeService;
import com.example.shiwu.service.BoxTwoService;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.ReceiveVolEleService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.service.UserService;
import com.example.shiwu.util.ArrayUtil;
import com.example.shiwu.util.ByteUtil;
import com.example.shiwu.util.Callback;
import com.example.shiwu.util.ContextVariable;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.FileDownUtil;
import com.example.shiwu.util.SharedPreferencesUtii;
import com.example.shiwu.util.SocketMergeCallBackUtils;
import com.example.shiwu.util.SocketMergeCallBackUtils;
import com.example.shiwu.util.SocketUtils;
import com.example.shiwu.util.SwitchBoxUtil;
import com.example.shiwu.util.WifiReceiver;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;


import org.apache.commons.lang3.ArrayUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.hutool.core.util.IdUtil;

public class GatherDataActivity extends AppCompatActivity {
    public static boolean receive_one_field_sta = true;
    private DynamicLineChartManager dynamicLineChartManager;
    public ImageView title_back, no_data_img;
    public TextView stop_gather, start_gather, plan_break, permutations, waveform, frequency_spectrum;

    private SharedPreferences.Editor editor;
    private SharedPreferences preferences;

    private ImageView img;


    private Boolean bool1 = true;
    private int abmn_indx = 0;
    private Python py;
    private PyObject pyobj, pyplot, pyobj1, pyobj2, pyobjfft;
    private static Object lockObject = new Object();

    public JSONArray jsonArray;
    public byte[] bytesData;
    public int startCount = 0;
    public int gatherType = 1;
    public boolean startPause = false;
    private OutputStream mOutStream;
    private InputStream mInStream;

    private HandlerThread mHandlerThread;
    //子线程中的Handler实例。
    private Handler mSubThreadHandler;

    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    public int count_byte = 0;
    private String cmd_index_len = "";//消息的id 10
    private int success_count = 0;
    private int header_cou = 0;
    public String receiveDataAll = "";
    private Integer packet_indx = 0;
    private Integer packet_lens = 0;//总包数 1536倒计数到0 packet_lens=0, bak_packet_lens=512, rec_count=512 self.send("kConfirm",rec_count)
    private int loding_count = 0;
    public static int toatalByte = 0;

    public Socket mSocket;
    private final int DEFAULT_PORT = 8086;
    private String mIpAddress = ContextVariable.IP; //服务端ip地址
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private static final String IP_ADDRESS = "ip_address";
    private static final String CLIENT_PORT = "client_port";
    private static final String CLIENT_MESSAGETXT = "client_msgtxt";
    public final int MSG_SUCCESS = 1;
    public String IPValues = "";
    private static final int MSG_RECEIVE_DATA = 9;
    private static final int MSG_RECEIVE_TU_DATA = 10;
    private static final int MSG_RECEIVE_PAI_DATA = 11;
    private static final int MSG_RECEIVE_BO_DATA = 12;
    private static final int MSG_RECEIVE_PIN_DATA = 13;
    private static final int MSG_RECEIVE_SECTION_DATA = 14;
    private static final int MSG_RECEIVE_OVER_DATA = 15;
    private static final int MSG_RECEIVE_FAIL_DATA = 16;
    private static final int MSG_RECEIVE_TOAST_DATA = 17;

    private static final int MSG_RECEIVE_ALARM = 18;
    private static final int MSG_BING_ERROR_DATA = 19;
    private int mSocketConnectState = STATE_DISCONNECTED;

    private SendsService sendsService;
    private ItemsService itemsService;
    private ImageView mChart1, mChart2, mChart3, mChart4;
    private String[] freqData, modeData, freqFilterData, repeatData, valtageData;
    private String permutationMode;//采集模式，加到CVS里
    private Integer devtype;//采集模式0-4
    private int sf = 0;
    private int srepeat = 0;
    private int svaltage = 0;
    private ArrangeService arrangeService;
    private DeviceService deviceService;
    private List<Arrange> arrangeLis;

    private byte[] byt;
    private String simpleUUID;
    private MyQueue queue;
    private MyQueue queueMsg;
    private MyQueue queueAlarm;
    private String vol_ele = "";
    private String fileName = "";
    private String saveTime;
    private String vol_ele_noindx = "";
    private String str_vol_ele_noindx = "";
    private int packet_lens_old = 0;
    public static int packet_indx_old = 0;
    private String tx_voltage_data = "";
    private String tx_current_data = "";
    private String rx_voltage_data = "";
    private Integer rx_voltage_data_len = 0;
    private Integer cvs_line = 0, csv_line_count = 0, count_line = 0;
    private boolean back_over = false; //biaoshi
    private int receive_packet_indx_count = 0;
    private byte[] buffer = null;
    private Context myContext;
    private String sn;
    private WifiReceiver wifiReceiver;
    private String userName;
    //private SocketUtils socketUtils;
    private BroadcastReceiver networkReceiver;
    private SocketMergeCallBackUtils socketUtils;
    private ReceiveVolEleService receiveVolEleService;
    private UserService userService;
    private AlarmService alarmService;
    private Boolean receive_sta = false;//采集一次后true 过滤vol_ele的title
    private byte[] data, data2, data3;
    private String[] abmnlis = null;
    private int msg_sueecss_count = 0;
    private Boolean startGater = false;
    private Boolean errorRepeat = false;
    private long timeouts = 17500;
    public MyThread myThread;
    public static Boolean returnSta = true;
    private String dtype, shape, abmn, abmnStr;
    private int dtypelen, dtypelen0, dtypelenAbmn, ns, abmnLen, boxId, boxInx;
    ;
    private int inclickGatherCount;//点击采集按钮次数
    private int packet_indx1 = 0;
    private TextView send_poiont_val;
    private TextView receive_poiont_val;
    private TextView filter_type_val;
    private TextView device_type_val;
    private TextView receive_voltage_val;
    private TextView send_frequency_val;
    private String freq_Indx, repeatUnm;

    private String[] clearStrLisAll;
    private Integer rec_count_s = 0;

    private int num_points = 0; // 数据点 （128,258,512）
    private int filter = 0;//滤波类型 0不滤波 1低频滤波 2阻带滤波
    private int interval = 0;//最大间隔系数
    private String send_piont = "";//发射点
    private String receive_piont = "";//接收点
    public static Boolean recv_float_bool = false;
    public Boolean recv_float_bool2 = true;
    private String itemsId;
    private String rx_voltage_data_all = "";
    private Boolean bool = false;
    private String send_frequency_value, send_repeat_value, send_voltage_value;
    private ArrayList<Double[]> tx_c_rx_v_lis = null;
    // private JSONObject jb = null;
    private JSONObject jb_tu = new JSONObject();
    private int error_jb_tu = 0;
    private JSONObject jsonObjectMsg = new JSONObject();
    private JSONArray jbA = null;
    private int[] repate_indx = null;
    private String jb_tu_str;
    private DataParseUtil dataParseUtil;
    private Items items;
    private StringBuffer rx_voltage_data1;
    private StringBuffer rx_voltage_data_all1;
    Boolean errorCount = true;
    public Boolean anewSta = true;
    private String[] boxlis = null;
    private ArrayList<String> alis = null;
    private ArrayList<String> boxLatLon;
    private BoxOneService boxOneService;
    private BoxTwoService boxTwoService;
    private BoxThreeService boxThreeService;
    private BoxFourService boxFourService;
    private BoxFiveService boxFiveService;
    private BoxSixService boxSixService;
    private BoxSevenService boxSevenService;
    private BoxEightService boxEightService;
    private BoxNineService boxNineService;
    private BoxTenService boxTenService;
    private DatabaseHelper dbHelper;
    public static Boolean errorSta = false;
    public static Boolean boolErr = true;
    private StringBuffer tx_current_data1;
    private Boolean myBool = false;
    private Boolean myBool2 = false;
    private Boolean myBool3 = false;
    private Boolean myBool4 = false;
    private Boolean myBool5 = false;
    Boolean headSta = false;
    Boolean indxSta = false;
    Boolean txvSta = false;
    Boolean txcSta = false;
    Boolean rxvSta = false;
    private String deviceId;//设备ID 用于存储ALARM
    private String alarmVal;// alarm内容
    private boolean alarmSta = false;
    public int rec_count = 0;
    private Integer packet_indx_111 = 0;
    private int test_cout = 0;
    public int reconnectionCount = 0;//重连次数，超过10次 采集失败
    private Boolean bo1 = true;
    public int error = 0;
    private Integer model = 0;//装置类型
    private BigDecimal resistivityVal;//装置系数K
    private ArrayList<ArrayList<BigDecimal>> VIRO = new ArrayList<ArrayList<BigDecimal>>();//电压、电流、电阻率数组用于原始数据的归一处理
    private ArrayList<BigDecimal> VIRO_part = null;//电压、电流、电阻率数组用于原始数据的归一处理的子集
    private BigDecimal kVal;//装置系数K
    private static String saveCvsFileName, senduId, errorPoint = "";
    public int errorPointLine = 0; // 错误的行 saveCsv（）继续使用

    private Handler mHandler = new Handler() {
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SUCCESS:
                    img.setImageBitmap(BitmapFactory.decodeByteArray((byte[]) msg.obj, 0, ((byte[]) msg.obj).length));
                    if (msg.arg1 == 1) {
                        try {
                            bytesData = pyobj.callAttr("ERTPlot", jsonArray.get(0).toString(), 0).toJava(byte[].class);
                            Thread.sleep(100);
                            img.setImageBitmap(BitmapFactory.decodeByteArray((byte[]) msg.obj, 0, ((byte[]) msg.obj).length));
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    break;

//                case MSG_SOCKET_CONNECT:
                // 初始化 SocketUtils，替换成你的服务器地址和端口

                case MSG_RECEIVE_TU_DATA:
                    //拟断面
                    planBreak();
                    int idex = msg.arg1;
                    String obj1 = (String) msg.obj;
                    List<byte[]> fio = null;
                    int ns1 = 0;
                    if(null != errorPoint){
                        ns1 = ns - Integer.parseInt(errorPoint);
                    }else {
                        ns1 =  ns;
                    }
                    if (null != senduId && !senduId.equals("") ) {
                        fio = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex), ns1, 0,
                                obj1, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,senduId);

                        senduId = null;
                    }else {
                        fio = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex), ns1 , 0,
                                obj1, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,simpleUUID);
                    }
                    if (fio.size() > 1) {
                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(1), 0, fio.get(1).length));
                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(2), 0, fio.get(2).length));
                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(3), 0, fio.get(3).length));
                        start_gather.setEnabled(true);
                        start_gather.setText("采集数据");
                        myThread.pauseThread();
                        //savebitmap(BitmapFactory.decodeByteArray(fio.get(0), 0, fio.get(0).length), "niduan");
                        savebitmap(BitmapFactory.decodeByteArray(fio.get(1), 0, fio.get(1).length), "pailie");
                        savebitmap(BitmapFactory.decodeByteArray(fio.get(2), 0, fio.get(2).length), "boxing");
                        savebitmap(BitmapFactory.decodeByteArray(fio.get(3), 0, fio.get(3).length), "pinpu");
                    }
                    savebitmap(BitmapFactory.decodeByteArray(fio.get(0), 0, fio.get(0).length), "niduan");
                    mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio.get(0), 0, fio.get(0).length));

                    break;
                case MSG_RECEIVE_PAI_DATA:
                    //排列图示
                    permutations();
                    int idex2 = msg.arg1;
                    String obj2 = (String) msg.obj;
                    List<byte[]> fio2 = null;
                    int ns2 = 0;
                    if(null != errorPoint){
                        ns2 = ns - Integer.parseInt(errorPoint);
                    }else {
                        ns2 =  ns;
                    }
                    if (null != senduId) {
                        fio2 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex2), ns2, 1,
                                obj2, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,senduId);
                        senduId = null;
                    }else {
                        fio2 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex2), ns2, 1,
                                obj2, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,simpleUUID);
                    }
                    if (fio2.size() > 2) {
                        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(0), 0, fio2.get(0).length));
                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(1), 0, fio2.get(1).length));
                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(2), 0, fio2.get(2).length));
                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(3), 0, fio2.get(3).length));
                        start_gather.setEnabled(true);
                        start_gather.setText("采集数据");
                        myThread.pauseThread();
                    } else {
                        savebitmap(BitmapFactory.decodeByteArray(fio2.get(1), 0, fio2.get(1).length), "niduan");
                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio2.get(0), 0, fio2.get(0).length));

                    }
                    break;
                case MSG_RECEIVE_BO_DATA:
                    //实时波形
                    waveform();
                    String obj3 = (String) msg.obj;
                    int idex3 = msg.arg1;
                    List<byte[]> fio3 = null;
                    int ns3 = 0;
                    if(null != errorPoint){
                        ns3 = ns - Integer.parseInt(errorPoint);
                    }else {
                        ns3 =  ns;
                    }
                    if (null != senduId) {
                        fio3 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex3), ns3, 2,
                                obj3, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,senduId);
                        senduId = null;
                    }else {
                        fio3 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex3), ns3, 2,
                                obj3, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,simpleUUID);
                    }
                    if (fio3.size() > 2) {
                        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(0), 0, fio3.get(0).length));
                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(1), 0, fio3.get(1).length));
                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(2), 0, fio3.get(2).length));
                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(3), 0, fio3.get(3).length));
                        start_gather.setEnabled(true);
                        start_gather.setText("采集数据");
                        myThread.pauseThread();
                    } else {
                        savebitmap(BitmapFactory.decodeByteArray(fio3.get(1), 0, fio3.get(1).length), "niduan");
                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio3.get(0), 0, fio3.get(0).length));
                    }
                    break;
                case MSG_RECEIVE_PIN_DATA:
                    //频谱
                    frequencySpectrum();
                    String obj4 = (String) msg.obj;
                    int idex4 = msg.arg1;
                    List<byte[]> fio4 = null;
                    int ns4 = 0;
                    if(null != errorPoint){
                        ns4 = ns - Integer.parseInt(errorPoint);
                    }else {
                        ns4 =  ns;
                    }
                    if (null != senduId) {
                        fio4 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex4), ns4, 3,
                                obj4, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,senduId);
                        senduId = null;
                    }else {
                        fio4 = DataParseUtil.SectionArray(jb_tu_str, jsonObjectMsg.toString(), String.valueOf(idex4), ns4, 3,
                                obj4, freq_Indx, rx_voltage_data_len, num_points, num_points, filter, interval, model, dtypelen0,simpleUUID);
                    }
                    if (fio4.size() > 2) {
                        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(0), 0, fio4.get(0).length));
                        mChart2.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(1), 0, fio4.get(1).length));
                        mChart3.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(2), 0, fio4.get(2).length));
                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(3), 0, fio4.get(3).length));
                        start_gather.setEnabled(true);
                        start_gather.setText("采集数据");
                        myThread.pauseThread();
                    } else {
                        savebitmap(BitmapFactory.decodeByteArray(fio4.get(1), 0, fio4.get(1).length), "niduan");
                        mChart4.setImageBitmap(BitmapFactory.decodeByteArray(fio4.get(0), 0, fio4.get(0).length));
                    }
                    break;

                case MSG_RECEIVE_ALARM:
                    String obj5 = (String) msg.obj;
                    start_gather.setText(obj5);
                    break;
                case MSG_RECEIVE_DATA:
                    String[] vel = vol_ele.split(";");
                    //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
                    //String simpleUUID = IdUtil.simpleUUID();
                    FileDownUtil.saveFile(myContext, vel, simpleUUID);
                    List<ReceiveVolEle> lis = new ArrayList<ReceiveVolEle>();
                    ReceiveVolEle rve = null;
                    MyQueue queue1 = new MyQueue();
                    int ii = 0;
                    if (!receive_sta) {
                        ii = 1;
                    }
                    for (int i = ii; i < vel.length; i++) {
                        String vel_new = "";
                        vel_new = vel[i];
                        if (!vel_new.equals("")) {
                            String[] vel_new_lis = vel_new.split(",");
                            rve = new ReceiveVolEle();
                            for (int j = 0; j < vel_new_lis.length; j++) {
                                switch (j) {
                                    case 1:
                                        rve.setIndx(Integer.parseInt(vel_new_lis[j]));
                                        rve.setCreateTime(DateUtils.parseDate());
                                        rve.setGropId(simpleUUID);
                                        Items items = findSelectItem();
                                        rve.setItemId(items.getId());
                                        break;

                                    case 7:
                                        rve.setTxv(vel_new_lis[j]);
                                        break;
                                    case 8:
                                        rve.setTxc(vel_new_lis[j]);
                                        break;

                                    case 9:
                                        rve.setRxv(vel_new_lis[j]);
                                        break;
                                }

                            }
                            lis.add(rve);
                            queue1.enQueue(rve);
                            ReceiveVolEle rveDo = (ReceiveVolEle) queue1.deQueue();
                            //queue.clear();
                            if (rve != null && rve.getIndx() != null) {
                                receiveVolEleService.save(rve);
                            }
                            receive_sta = true;
                        }

                    }
                    break;
                case MSG_RECEIVE_OVER_DATA:
                    Toast.makeText(myContext, "采集数据结束！", Toast.LENGTH_SHORT).show();
                    try {
                        DataParseUtil.clearPkl(simpleUUID);//清除pkl
                        Thread.sleep(1000);
                        startGater = false;
                        msg_sueecss_count = 0;
                        SocketMergeCallBackUtils.success_count = 0;
                        start_gather.setText("采集结束");
                        start_gather.setEnabled(false);
                        senduId = null;

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case MSG_RECEIVE_FAIL_DATA:
                    Toast.makeText(myContext, "采集数据失败！", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_RECEIVE_TOAST_DATA:
                    String msgData = (String) msg.obj;
                    Toast.makeText(myContext, msgData, Toast.LENGTH_SHORT).show();
                    break;
                case MSG_BING_ERROR_DATA:
                    Toast.makeText(myContext, "设备绑定失败！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };



    public JSONObject initJson() {
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        //Items items = null;
        Arrange arrange = new Arrange();
        num_points = packet_lens_old / 3;
        try {
            //items = findSelectItem();
            if (null != items) {
                arrange.setItemId(items.getId());

                Arrange arrange2 = arrangeLis.get(0);
                interval = Integer.parseInt(arrange2.getInterval());
                jsonObject.put("num_electrodes", "20");
                jsonObject.put("Max_n_spacing", "20");
                jsonObject.put("Aspacing", arrange2.getElectrodeDistance());
                jsonObject.put("ChnNO", "10");
                //jsonObject.put("ABMN", abmnStr.replace(",",""));
                jsonObject.put("ABMN", abmn);
                jsonObject.put("TXFrq", freq_Indx);
                jsonObject.put("TXDuty", "10");
                jsonObject.put("CycleNO", "10");
                jsonObject.put("StackNO", send_repeat_value);
                jsonObject.put("RXSR", num_points);
                jsonObject.put("dtype", arrange2.getDtype());
                jsonObject.put("shape", arrange2.getShape());
                //jsonObject.put("path", "/data/data/com.example.shiwu/files/1-9f0a4c7f39674bb68e1b20b0505044c3.cvs");
                jsonObject2.put("Aspacing", arrange2.getElectrodeDistance());
                jsonObject2.put("ABMN", abmn);
                jsonObject2.put("dtype", arrange2.getDtype());
                jsonObject2.put("shape", arrange2.getShape());
                ns = dataParseUtil.ERTuiSectionNs(jsonObject2.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    // 自定义广播接收器类
    public class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                // 获取连接管理器
                ConnectivityManager connectivityManager =
                        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

                // 获取当前网络信息
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

                // 判断网络连接状态
                if (networkInfo != null && networkInfo.isConnected()) {
                    // 网络已连接
                    String networkType = "";
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        networkType = "WiFi";
                    } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        networkType = "移动数据";
                    }
                   // Toast.makeText(context, "已连接到网络: " + networkType, Toast.LENGTH_SHORT).show();
                    Toast.makeText(myContext, "网络已连接！", Toast.LENGTH_SHORT).show();
                    queue = new MyQueue();
                    queueMsg = new MyQueue();
                    queueAlarm = new MyQueue();
                    dataParseUtil = new DataParseUtil();
                    rx_voltage_data1 = new StringBuffer();
                    rx_voltage_data_all1 = new StringBuffer();
                    deviceService = new DeviceService();

                    dbHelper = new DatabaseHelper(myContext);
                    initService();
                    setContentView(R.layout.activity_gather);
                    mChart1 = findViewById(R.id.imageViews);
                    mChart2 = findViewById(R.id.imageViews2);
                    mChart3 = findViewById(R.id.imageViews3);
                    mChart4 = findViewById(R.id.imageViews4);
                    Resources res = getResources();
                    freqData = res.getStringArray(R.array.freqData);
                    modeData = res.getStringArray(R.array.modeData);
                    freqFilterData = res.getStringArray(R.array.freqFilter);
                    repeatData = res.getStringArray(R.array.repeatCount);
                    valtageData = res.getStringArray(R.array.valtageData);
                    arrangeService = new ArrangeService();
                    receiveVolEleService = new ReceiveVolEleService();
                    alarmService = new AlarmService();
                    items = findSelectItem();
                    rx_voltage_data1 = new StringBuffer();
                    tx_current_data1 = new StringBuffer();
                    boxId = getBoxInx();
//                    Intent intent1 = getIntent();
//                    if (intent1 != null) {
//                        senduId = intent.getStringExtra("senduId");
//                        errorPoint = intent.getStringExtra("errorPoint");
//
//                        String errorPointLine2 = intent.getStringExtra("errorPointLine");
//                        if(null != errorPointLine2){
//                            errorPointLine = Integer.parseInt(errorPointLine2);
//                            cvs_line = 1;
//                            csv_line_count = errorPointLine;
//                        }
//
//                        System.out.println(senduId);
//                    }

                    boolean bool = getViewInit();

                    title_back.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (startCount == 1|| startCount ==0) {
                                AlertDialog.Builder dialog = new AlertDialog.Builder(myContext);//通过AlertDialog.Builder创建出一个AlertDialog的实例
                                dialog.setTitle("提示");//设置对话框的标题
                                dialog.setMessage("采集数据中请勿离开页面,否则会中断采集!");//设置对话框的内容
                                dialog.setCancelable(false);//设置对话框是否可以取消
                                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {//确定按钮的点击事件

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        recv_float_bool = false;
                                        receive_one_field_sta = false;
                                        //myThread.interrupt();
                                        if(myThread != null){
                                            myThread.pauseThread();
                                        }

                                        dtypelen = 0;
                                        dtypelen0 = 0;
                                        try {
                                            Thread.sleep(100);
                                            GatherDataActivity.this.finish();
                                        } catch (InterruptedException e) {
                                            throw new RuntimeException(e);
                                        }

                                    }
                                });
                                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {//取消按钮的点击事件
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                dialog.show();//显示对话框
                            } else {
                                GatherDataActivity.this.finish();
                            }
                        }
                    });
                    plan_break.setTextColor(Color.parseColor("#FF007AFF"));
                    plan_break.setTextSize(18);

                    start_gather.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            DataParseUtil.ClosePlt();
                            if(!wifiReceiver.bool){
                                Toast.makeText(myContext, "网络未连接！", Toast.LENGTH_SHORT).show();
                                return;
                            }
                            if (socketUtils == null) {
                                socketUtils = SocketMergeCallBackUtils.getInstance(myContext);

                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }

                            } else {
                                System.out.println("------------Gather_SocketMergeCallBackUtils.resumeThread()------------");
                                //socketUtils.startListening();
                                //SocketMergeCallBackUtils.resumeThread();
                            }
                            //msg_sueecss_count=0;
                            SocketMergeCallBackUtils.success_count = 0;

                            myThread = new MyThread();
                            startCount = 1;
                            start_gather.setText("采集中..");
                            start_gather.setEnabled(false);
                            System.out.println("-------------------采集中---------------");
                            sendsService = new SendsService();
                            itemsService = new ItemsService();
                            Items items = new Items();
                            items.setStatus(1);
                            List<Items> items1 = itemsService.getItems(items);
                            Sends sends1 = new Sends(items1.get(0).getId());
                            sends1.setType(0);
                            List<Sends> sends = sendsService.getSends(sends1);
                            Arrange arrange1 = new Arrange();
                            arrange1.setItemId(items1.get(0).getId());
                            arrangeLis = arrangeService.getArrange(arrange1);
                            Boolean boo = sendMcu(sends.get(0), items1.get(0).getId());
                            if (null != senduId) {
                                simpleUUID = senduId;
                                fileName = items1.get(0).getId() + "-" + senduId;
                                saveTime = sends.get(0).getCreateTime().substring(0, 10);
                                //cvs_line = 1;
                                //dtypelen0 = Integer.parseInt(errorPoint);
                                Thread.State state = myThread.getState();
                                System.out.println(state);
                                myThread = null;
                                if (null != myThread) {

                                    try {
                                        myThread.interrupt();

                                        Thread.sleep(10);
                                        myThread.start();
                                    } catch (InterruptedException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                                myThread = new MyThread();
                                myThread.start();
                            } else {
                                if (boo) {
                                    simpleUUID = IdUtil.simpleUUID();
                                    saveTime = DateUtils.parseYmdDate();
                                    saveSends(sends.get(0));
                                }
                            }


                        }
                    });

                    try {
                        initPython(myContext);

                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    // 网络已断开
                    //Toast.makeText(context, "网络连接已断开", Toast.LENGTH_SHORT).show();
                    Toast.makeText(myContext, "网络未连接！", Toast.LENGTH_SHORT).show();
                    //return;
                    setContentView(R.layout.activity_gather);
                    mChart1 = findViewById(R.id.imageViews);
                    mChart2 = findViewById(R.id.imageViews2);
                    mChart3 = findViewById(R.id.imageViews3);
                    mChart4 = findViewById(R.id.imageViews4);
                    title_back = findViewById(R.id.gather_title_back);
                    title_back.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (startCount == 1|| startCount ==0) {
                                AlertDialog.Builder dialog = new AlertDialog.Builder(myContext);//通过AlertDialog.Builder创建出一个AlertDialog的实例
                                dialog.setTitle("提示");//设置对话框的标题
                                dialog.setMessage("采集数据中请勿离开页面,否则会中断采集!");//设置对话框的内容
                                dialog.setCancelable(false);//设置对话框是否可以取消
                                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {//确定按钮的点击事件

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        try {
                                            Thread.sleep(100);
                                            GatherDataActivity.this.finish();
                                        } catch (InterruptedException e) {
                                            throw new RuntimeException(e);
                                        }

                                    }
                                });
                                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {//取消按钮的点击事件
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });
                                dialog.show();//显示对话框
                            } else {
                                GatherDataActivity.this.finish();
                            }
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        myContext = this;
        //wifiReceiver = new WifiReceiver();
        Intent intent = getIntent();
        if (intent != null) {
            senduId = intent.getStringExtra("senduId");
            errorPoint = intent.getStringExtra("errorPoint");

            String errorPointLine2 = intent.getStringExtra("errorPointLine");
            if(null != errorPointLine2){
                errorPointLine = Integer.parseInt(errorPointLine2);
                cvs_line = 1;
                csv_line_count = errorPointLine;
            }

            System.out.println(senduId);
        }

        // 注册网络连接变化的广播接收器
        networkReceiver = new NetworkChangeReceiver();
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkReceiver, filter);
        deviceService = new DeviceService();
        userService = new UserService();
        User user = userService.getLoginUser();
        userName = user.getName();
        List<Device> deviceList = deviceService.getDevice(new Device());
        if(deviceList.size()>0) {
            sn = deviceList.get(0).getSn();
            String deviceIds = SharedPreferencesUtii.getSharedPreferences("deviceId", myContext);
            if (!deviceIds.equals("")) {
                if (userName.equals("user")) {
                    if (!deviceIds.equals(sn)) {
                        Message msg1 = new Message();
                        msg1.what = MSG_BING_ERROR_DATA;
                        mHandler.sendMessage(msg1);
                        return;
                    }
                }
            }
        }
        File downloadFile = new File(ContextVariable.IMG_DOWN_NAME);
        try {
            if (!downloadFile.exists()) {
                downloadFile.mkdir();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//    @Override
//    protected void onStart() {
//        super.onStart();
//        android.os.Process.killProcess(android.os.Process.myPid());
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出HandlerThread的Looper循环。
        System.out.println("---------------------- onDestroy --------------------");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        unregisterReceiver(networkReceiver);
//        if (socketUtils != null) {
//            try {
//                SocketMergeCallBackUtils.clrearBuffer();
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
        if (socketUtils != null) {
            socketUtils.isReConnect = true;
            socketUtils.releaseSocket();
        }
        if (myThread != null) {
            //myThread.interrupt();
            myThread.pauseThread();
            recv_float_bool = false;
            receive_one_field_sta =  false;

        }

        dtypelen = 0;
        dtypelen0 = 0;
        startGater = false;
        msg_sueecss_count = 0;
        SocketMergeCallBackUtils.success_count = 0;
    }

    public int getBoxInx() {
        Items items = findSelectItem();
        itemsId = items.getId().toString();
        Arrange arrange1 = new Arrange();
        arrange1.setItemId(Integer.valueOf(itemsId));
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
        abmnLen = arrangeLis.get(0).deviceTypeLen + 1;
        Device device = new Device();
        device.setItemId(itemsId);
        List<Device> lis = deviceService.getDevice(device);
        int count = 0;
        if (lis.size() == 0) {
            Toast.makeText(myContext, "网络连接失败！", Toast.LENGTH_SHORT).show();
            //return;
            count = 0;
        } else if (lis.size() > 0) {
            String box = lis.get(0).getBox().replaceAll(" ", "");
            boxlis = box.split(",");
            alis = new ArrayList();
            for (int i = 0; i < boxlis.length; i++) {
                if (!boxlis[i].equals("00")) {
                    alis.add(boxlis[i]);
                }
            }
            count = abmnLen / alis.size();
        }

        return count;
    }

    private boolean socketListener() {
        Timer timer1 = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (socketUtils.socketReconnection) {
                    Log.e("socketReconnection", "-------------socketReconnection false-----------");
                    socketUtils.socketReconnection = false;
                    recv_float_bool = false;
                    return;
                }
            }
        };
        timer1.schedule(task, 0, timeouts);
        timer1.cancel();
        if(socketUtils == null){
            socketUtils = SocketMergeCallBackUtils.getInstance(myContext);
        }
        if (recv_float_bool = false) {
            return false;
        }

        //kSetTxWaveWithParam 3
        if (anewSta) {
            if (data != null) {

                SocketMergeCallBackUtils.writeMsgByte(data, new Callback() {
                    @Override
                    public void onSuccess(byte[] data) {
                        Log.i("SocketClient111111111111", "kSetTxWaveWithParam 3 Text sent successfully============= " + new String(data));
                        //Log.i("SocketClient", "kSetTxWaveWithParam 3 Text sent successfully============= " + Arrays.toString(data));
                        String msg = new String(data);
                        if (!msg.equals("")) {
//                            if (msg.contains(";")) {
//                                String[] lis1 = msg.split(";");
//                                if (lis1.length == 1) {
//                                    Boolean bl = getStatus(lis1[0].trim() + ";");
//                                    if (bl) {
//                                        myBool5 = sendkClearAllMuxBoxConnectOrder();
//                                        return;
//                                    }
//                                } else {
//                                    for (int i = 0; i < lis1.length; i++) {
//                                        Boolean bl = getStatus(lis1[i].trim() + ";");
//                                        if (bl) {
//                                            myBool5 = sendkClearAllMuxBoxConnectOrder();
//                                            return;
//                                        }
//                                    }
//                                }
//
//                            } else {
//                                Log.i("SocketClient", "kSetTxWaveWithParam 3 ----1 Text sent successfully============= " + Arrays.toString(data));
//                                stopMyThread();
//                                return;
//
//                            }

                            if (msg.equals("0,wait;")) {
                                try {
                                    Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }

                                byte[] myByte = socketUtils.readDataHeadCheckPole();// 消息状态
                                String myByteStr = new String(myByte);
                                if (myByteStr.equals("0,Success;")) {
                                    myBool5 = sendkClearAllMuxBoxConnectOrder();
                                    return;
                                }
                            } else if (msg.equals("0,Success;")) {
                                myBool5 = sendkClearAllMuxBoxConnectOrder();
                                return;

                            }else{
                                getStatus(msg);
                            }
                        }
                    }

                    @Override
                    public void onFailure(String errorMessage) {
                        Log.e("SocketClient", "kSetTxWaveWithParam 3 Failed to send text: " + errorMessage);
                    }
                });
            }
        }
        return myBool5;
    }

    /**
     * kClearAllMuxBoxConnect 15
     */
    private boolean sendkClearAllMuxBoxConnectOrder() {
        Timer timer1 = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (socketUtils.socketReconnection) {
                    Log.e("socketReconnection", "-------------socketReconnection false-----------");
                    socketUtils.socketReconnection = false;
                    recv_float_bool = false;
                    return;
                }
            }
        };
        timer1.schedule(task, 0, timeouts);
        timer1.cancel();
        if (recv_float_bool = false) {
            return false;
        }
        try {
            Boolean clrearBuffer = socketUtils.clrearBufferNew();
        } catch (IOException e) {
            e.printStackTrace();
        }
        SocketMergeCallBackUtils.writeMsgByte(data2, new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "kClearAllMuxBoxConnect 15 Text sent successfully ============= " + new String(data));
                //Log.i("SocketClient", "kClearAllMuxBoxConnect 15 Text sent successfully ============= " + Arrays.toString(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    if (msg.contains(";")) {
                        String[] lis1 = msg.split(";");
                        if (lis1.length == 1) {
                            Boolean bl = getStatus(lis1[0].trim() + ";");

                            if (bl) {
                                myBool4 = sendkSetMuxBoxConnectOrder();
                                return;
                            } else {
//                                if(lis1[0].trim().equals("0,wait")){
//                                    //bl = true;
//                                    try {
//                                        Thread.sleep(1500);
//                                    } catch (InterruptedException e) {
//                                        throw new RuntimeException(e);
//                                    }
//                                }
                                Boolean bool = true;
                                while (bool) {
                                    byte[] by = SocketMergeCallBackUtils.readDataHead();
                                    if (by.length == 0) {
                                        myThread.pauseThread();
                                        Message msg1 = new Message();
                                        msg1.what = MSG_RECEIVE_FAIL_DATA;
                                        mHandler.sendMessage(msg1);
                                        bool = false;
                                        Log.e("kClearAllMuxBoxConnect 15", "======================== kClearAllMuxBoxConnect 15 false ================");
                                        break;
                                    }
                                    String bystr = new String(by);
                                    System.out.println("======================== Success15_00000 bad_param ================" + bystr);

                                    if (!bystr.equals("")) {
                                        if (bystr.equals("0,Success;")) {
                                            System.out.println("======================== Success15_0 bad_param ================" + bystr);
                                            myBool4 = sendkSetMuxBoxConnectOrder();
                                            return;
                                        } else if (bystr.equals("0,Timeout;")) {
                                            sendkClearAllMuxBoxConnectOrder();
                                            return;
                                        } else {
                                            getStatus(bystr);
                                        }
                                    }
                                }
                                if (!bool) {
                                    myBool4 = false;
                                    Log.e("kClearAllMuxBoxConnect 15", "======================== kClearAllMuxBoxConnect 15 false11111111111 ================");
                                    return;
                                }
                            }
                        }
//                        else {
//                            for (int i = 0; i < lis1.length; i++) {
//                                Boolean bl = getStatus(lis1[i].trim() + ";");
//
//                                if (bl) {
//                                    myBool4 = sendkSetMuxBoxConnectOrder();
//                                    return;
//                                } else {
//                                    if (lis1[i + 1].trim().equals("0,Success")) {
//                                        System.out.println("======================== Success15_1 bad_param ================" + lis1[i + 1].trim());
//                                        myBool4 = sendkSetMuxBoxConnectOrder();
//                                        return;
//                                    } else {
////                                        if(lis1[0].trim().equals("0,wait")){
////                                            //bl = true;
////                                            try {
////                                                Thread.sleep(1500);
////                                            } catch (InterruptedException e) {
////                                                throw new RuntimeException(e);
////                                            }
////                                        }
//                                        Boolean bool = true;
//                                        while (bool) {
//                                            byte[] by = SocketMergeCallBackUtils.readDataHead();
//                                            if(by.length == 0){
//                                                return;
//                                            }
//                                            String bystr = new String(by);
//                                            if (!bystr.equals("")) {
//                                                if (bystr.equals("0,Success;")) {
//                                                    System.out.println("======================== Success15_2 bad_param ================" + bystr);
//                                                    myBool4 = sendkSetMuxBoxConnectOrder();
//                                                    return;
//                                                }
//                                            }
//                                        }
//                                    }
//
//                                }
//                            }
//                        }
                    }

                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "kClearAllMuxBoxConnect 15 Failed to send text: " + errorMessage);
            }
        });
        return myBool4;
    }


    /**
     * kSetMuxBoxConnect 2
     */
    private boolean sendkSetMuxBoxConnectOrder() {
        Timer timer1 = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (socketUtils.socketReconnection) {
                    Log.e("socketReconnection", "-------------socketReconnection false-----------");
                    socketUtils.socketReconnection = false;
                    recv_float_bool = false;
                    return;
                }
            }
        };
        timer1.schedule(task, 0, timeouts);
        timer1.cancel();
        if (recv_float_bool = false) {
            return false;
        }
        try {
            Boolean clrearBuffer = socketUtils.clrearBufferNew();
        } catch (IOException e) {
            e.printStackTrace();
        }
        SocketMergeCallBackUtils.writeMsgByte(data3, new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "kSetMuxBoxConnect 2 Text sent successfully ============= " + new String(data));
                //Log.i("SocketClient", "kSetMuxBoxConnect 2 Text sent successfully ============= " + Arrays.toString(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    if (msg.contains(";")) {
                        String[] lis1 = msg.split(";");
                        if (lis1.length == 1) {
                            Boolean bl = getStatus(lis1[0].trim() + ";");

                            if (bl) {
                                myBool3 = sendkPcResetAdcLogicOrder();
                                return;
                            } else {
//                                if(lis1[0].trim().equals("0,wait")){
//                                    //bl = true;
//                                    try {
//                                        Thread.sleep(1500);
//                                    } catch (InterruptedException e) {
//                                        throw new RuntimeException(e);
//                                    }
//                                }
                                Boolean bool = true;
                                while (bool) {
                                    byte[] by = SocketMergeCallBackUtils.readDataHead();
                                    if(by.length == 0){
                                        return;
                                    }
                                    String bystr = new String(by);
                                    Boolean bl1 = getStatus(bystr);
                                    if (bl1) {
                                        myBool3 = sendkPcResetAdcLogicOrder();
                                        return;
                                    }
                                }
                            }
                        } else {
                            for (int i = 0; i < lis1.length; i++) {
                                Boolean bl = getStatus(lis1[i].trim() + ";");

                                if (bl) {
                                    myBool3 = sendkPcResetAdcLogicOrder();
                                    return;
                                } else {
//                                    if(lis1[0].trim().equals("0,wait")){
//                                        //bl = true;
//                                        try {
//                                            Thread.sleep(1500);
//                                        } catch (InterruptedException e) {
//                                            throw new RuntimeException(e);
//                                        }
//                                    }
                                    Boolean bool = true;
                                    while (bool) {
                                        byte[] by = SocketMergeCallBackUtils.readDataHead();
                                        if(by.length == 0){
                                            return;
                                        }
                                        String bystr = new String(by);
                                        if (!bystr.equals("")) {
                                            if (bystr.equals("0,Success;")) {
                                                System.out.println("======================== Success0 bad_param ================" + bystr);
                                                myBool3 = sendkPcResetAdcLogicOrder();
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "kSetMuxBoxConnect 2 Failed to send text: " + errorMessage);
            }
        });
        return myBool3;
    }

    /**
     * kPcResetAdcLogic 23
     */
    private boolean sendkPcResetAdcLogicOrder() {
        Timer timer1 = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (socketUtils.socketReconnection) {
                    Log.e("socketReconnection", "-------------socketReconnection false-----------");
                    socketUtils.socketReconnection = false;
                    recv_float_bool = false;
                    return;
                }
            }
        };
        timer1.schedule(task, 0, timeouts);
        timer1.cancel();
        if (recv_float_bool = false) {
            return false;
        }
        try {
            Boolean clrearBuffer = socketUtils.clrearBufferNew();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = "23,r;";
        SocketMergeCallBackUtils.writeMsgByte(data.getBytes(), new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "kPcResetAdcLogic 23 Text sent successfully ============= " + new String(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    if (msg.contains(";")) {
                        String[] lis1 = msg.split(";");
                        if (lis1.length == 1) {
                            Boolean bl = getStatus(lis1[0].trim() + ";");

                            if (bl) {
                                myBool2 = sendkSartAdcSampleOnceOrder();
                                return;
                            } else {
//                                if(lis1[0].trim().equals("0,wait")){
//                                    try {
//                                        Thread.sleep(1500);
//                                    } catch (InterruptedException e) {
//                                        throw new RuntimeException(e);
//                                    }
//                                }
                                Boolean bool = true;
                                while (bool) {
                                    byte[] by = SocketMergeCallBackUtils.readDataHead();
                                    if(by.length == 0){
                                        return;
                                    }
                                    String bystr = new String(by);
                                    Boolean bl1 = getStatus(bystr);
                                    if (bl1) {
                                        myBool2 = sendkSartAdcSampleOnceOrder();
                                        return;
                                    }
                                }
                            }
                        } else {
                            for (int i = 0; i < lis1.length; i++) {
                                Boolean bl = getStatus(lis1[i].trim() + ";");

                                if (bl) {
                                    myBool2 = sendkSartAdcSampleOnceOrder();
                                    return;
                                } else {
//                                    if(lis1[0].trim().equals("0,wait")){
//
//                                        try {
//                                            Thread.sleep(1500);
//                                        } catch (InterruptedException e) {
//                                            throw new RuntimeException(e);
//                                        }
//                                    }
                                    Boolean bool = true;
                                    while (bool) {
                                        byte[] by = SocketMergeCallBackUtils.readDataHead();
                                        if(by.length == 0){
                                            return;
                                        }
                                        String bystr = new String(by);
                                        if (!bystr.equals("")) {
                                            if (bystr.equals("0,Success;")) {
                                                System.out.println("======================== Success0 bad_param ================" + bystr);
                                                myBool2 = sendkSartAdcSampleOnceOrder();
                                                return;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
            }
        });
        return myBool2;
    }

    /**
     * kSartAdcSampleOnce 4
     */
    private boolean sendkSartAdcSampleOnceOrder() {
        Timer timer1 = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                if (socketUtils.socketReconnection) {
                    Log.e("socketReconnection", "-------------socketReconnection false-----------");
                    socketUtils.socketReconnection = false;
                    recv_float_bool = false;
                    return;
                }
            }
        };
        timer1.schedule(task, 0, timeouts);
        timer1.cancel();
        if (recv_float_bool = false) {
            return false;
        }
        try {
            Boolean clrearBuffer = socketUtils.clrearBufferNew();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = "4,start;";
        SocketMergeCallBackUtils.writeMsgByte(data.getBytes(), new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "kSartAdcSampleOnce 4 Text sent successfully ============= " + new String(data));
                Log.i("SocketClient", "kSartAdcSampleOnce 4 Text sent successfully ============= " + Arrays.toString(data));
                myBool = true;

                String msg = new String(data);
                //msg = "0,Success;";
                if (!msg.equals("")) {
                    if (msg.contains(";")) {
                        String[] lis1 = msg.split(";");
                        if (lis1.length > 0) {
                            if (lis1[lis1.length - 1].equals("0,Success;")) {
                                Boolean bool = true;
                                ArrayList<Byte> bylist = new ArrayList<Byte>();
                                while (bool) {
                                    byte buf = SocketMergeCallBackUtils.read()[0];
                                    if (buf != 59) {
                                        bylist.add(buf);
                                    } else {
                                        bylist.add(buf);
                                        byte[] bytes = ByteUtil.convertByteListToArray(bylist);
                                        myBool = ReceiveDataForAnalyze(bytes);
                                        bool = true;
                                    }
                                }

                            } else if (lis1[lis1.length - 1].equals("0,wait;")) {
                                Boolean bool = true;
                                while (bool) {
                                    byte[] by = SocketMergeCallBackUtils.readDataHead();
                                    if(by.length == 0){
                                        return;
                                    }
                                    String bystr = new String(by);
                                    Boolean bl1 = getStatus(bystr);
                                    if (bl1) {
                                        byte[] bytes = ArrayUtil.subByte(by, 8, by.length);
                                        myBool = ReceiveDataForAnalyze(bytes);
                                        return;
                                    }
                                }
                            } else if (lis1[lis1.length - 1].equals("0,alarm")) {
                                Boolean bl1 = getStatus(msg);

                                stopMyThread();
                                myThread.pauseThread();
                            } else {
                                if (new String(data).equals("0,wait;0,Success;")) {
                                    System.out.println(" 4 ------------------ data == 0,wait;0,Success;");
                                    Boolean bool = true;
                                    ArrayList<Byte> bylist = new ArrayList<Byte>();
                                    while (bool) {
                                        byte buf = SocketMergeCallBackUtils.read()[0];
                                        if (buf != 59) {
                                            bylist.add(buf);
                                        } else {
                                            bylist.add(buf);
                                            byte[] bytes = ByteUtil.convertByteListToArray(bylist);
                                            myBool = ReceiveDataForAnalyze(bytes);
                                            bool = false;
                                        }
                                    }
                                } else {
                                    System.out.println(" 4 ------------------ data == " + Arrays.toString(data));
                                    if (new String(data).equals("0,Success;")) {
                                        Boolean bool = true;
                                        ArrayList<Byte> bylist = new ArrayList<Byte>();
                                        while (bool) {
                                            byte buf = SocketMergeCallBackUtils.read()[0];
                                            if (buf != 59) {
                                                bylist.add(buf);
                                            } else {
                                                bylist.add(buf);
                                                byte[] bytes = ByteUtil.convertByteListToArray(bylist);
                                                myBool = ReceiveDataForAnalyze(bytes);
                                                bool = false;
                                            }
                                        }
                                    } else {
                                        byte[] bytes = ArrayUtil.subByte(data, 10, 10);
                                        if (bytes[bytes.length - 1] != 59) {
                                            Boolean bool = true;
                                            byte[] bylist = new byte[1];
                                            while (bool) {
                                                byte buf = SocketMergeCallBackUtils.read()[0];
                                                bylist[0] = buf;
                                                byte[] bytes1 = (byte[]) ArrayUtils.toPrimitive(bylist);
                                                byte[] byAll = ArrayUtil.byteMerger(data, bytes1);
                                                System.out.println(" 4 ------------------ alldata == " + Arrays.toString(byAll));
                                                byte[] bytes2 = ArrayUtil.subByte(byAll, 10, 11);
                                                myBool = ReceiveDataForAnalyze(bytes2);
                                                bool = false;
                                                break;
                                            }
                                        } else {
                                            myBool = ReceiveDataForAnalyze(bytes);
                                        }
                                    }

                                }

                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "kSartAdcSampleOnce 4 Failed to send text: " + errorMessage);
            }
        });
        return myBool;
    }


    /**
     * 解析报文头信息及数据 10,1024,8....
     */
    public boolean ReceiveDataForAnalyze(byte[] data) {
        Boolean bool1 = false;
        List<Byte> datelist = new ArrayList<Byte>();
        try {
            byte buf = SocketMergeCallBackUtils.read()[0];
            System.out.println("=========== ReceiveDataForAnalyze buf ==========" + buf);
            receiveDataAll = new String(data, "iso8859-1");
            // test_cout += 1;
            Log.i("receiveDataAll", "============= 解析报文头信息及数据 receiveDataAll================" + receiveDataAll + "  test_cout= " + test_cout);

//            if(test_cout == 2){
//                Log.i("receiveDataAll", "============= 2=4=6 ==============");
//                Boolean clrearBuffer0 = socketUtils.clrearBuffer();
//                return false;
//            }

            if (!receiveDataAll.contains("10,")) {
                Log.i("receiveDataAll", "=============44444444444444444444444================");
                Boolean clrearBuffer = socketUtils.clrearBuffer();
                return false;
            }
            cmd_index_len = DataParseUtil.getDataForHeaderIndex(receiveDataAll);
            packet_indx = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[1]));
            packet_lens = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[2]));
            count_line = Integer.parseInt(repeatUnm) * (packet_lens / 3) * dtypelen;
            toatalByte = packet_lens / 3 * 21;
            System.out.println("--------ReceiveDataForAnalyze  packet_indx==" + packet_indx + " = " + packet_lens);
            packet_lens_old = packet_lens;
            packet_indx_old = packet_indx;
            SocketMergeCallBackUtils.packet_indx = packet_indx;
            DataParseUtil.setPageLens(packet_lens);
            receiveDataAll = "";
            bool1 = true;

        } catch (org.json.JSONException e) {
            // throw new RuntimeException(e);
            myThread.pauseThread();
            String msg1 = "采集数据失败！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } catch (InterruptedException e) {
            //throw new RuntimeException(e);
            myThread.pauseThread();
            String msg1 = "采集数据失败！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } catch (IOException e) {
            //throw new RuntimeException(e);
            myThread.pauseThread();
            String msg1 = "采集数据失败！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } finally {
        }
        return bool1;
    }

    /**
     * 解析报文头信息及数据 10,1024,8....
     */
    public boolean ReceiveDataForAnalyze1(byte[] data) {
        Boolean bool1 = false;
        List<Byte> datelist = new ArrayList<Byte>();
        try {
            byte buf = SocketMergeCallBackUtils.read()[0];
            System.out.println("=========== ReceiveDataForAnalyze buf ==========" + buf);
            receiveDataAll = new String(data, "iso8859-1");
            Log.i("receiveDataAll", "=============receiveDataAll================" + receiveDataAll);
//            test_cout += 1;
//            if(test_cout == 2){
//                Log.i("receiveDataAll", "============= 3333333333333333333333 ==============");
//                Boolean clrearBuffer = socketUtils.clrearBuffer();
//                stopMyThread();
//                return false;
//            }

            if (!receiveDataAll.contains("10,")) {
                Log.i("receiveDataAll", "=============555555555555555555555555================");
                stopMyThread();
                return false;
            }
            cmd_index_len = DataParseUtil.getDataForHeaderIndex(receiveDataAll);
            packet_indx = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[1]));
            packet_lens = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[2]));
            System.out.println("--------ReceiveDataForAnalyze  packet_indx==" + packet_indx + " = " + packet_lens);
            packet_lens_old = packet_lens;
            packet_indx_old = packet_indx;
            SocketMergeCallBackUtils.packet_indx = packet_indx;
            DataParseUtil.setPageLens(packet_lens);
            receiveDataAll = "";
            bool1 = true;

        } catch (org.json.JSONException e) {
            // throw new RuntimeException(e);
            myThread.pauseThread();
            String msg1 = "采集数据失败！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } catch (InterruptedException e) {
            //throw new RuntimeException(e);
            myThread.pauseThread();
            String msg1 = "采集数据失败！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } catch (IOException e) {
            //throw new RuntimeException(e);
            myThread.pauseThread();
            String msg1 = "采集数据失败！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } finally {
        }
        return bool1;
    }

    /**
     * 查询告警，并写入数据库
     * 1.发送18，get;读取success后截取数据，
     * 2.调用getAlarm13方法 发送13,update;命令
     */
    private void getAlarm18() {
        String data = "18,get;";
        SocketMergeCallBackUtils.writeMsg18(data, new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "Alarm 18 Text sent successfully ============= " + new String(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    String msglis_18 = ByteUtil.byteTransformAscil(data);
                    //System.out.println("  msglis_18 ===================="+ msglis_18);
                    deviceId = msglis_18.split(",")[1];//固件版本
                    if (!deviceId.equals("")) {
                        //读取success后截取数据，再发送13命令
                        getAlarm13();
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Alarm 18 Failed to send text: " + errorMessage);
            }
        });
    }

    private void getAlarm13() {
        String data = "13,update;";
        SocketMergeCallBackUtils.writeMsg14(data, new Callback() {
            @Override
            public void onSuccess(byte[] data) throws UnsupportedEncodingException {
                Log.i("SocketClient", "Alarm 13 Text sent successfully ============= " + new String(data, "utf-8"));
                String msg = Arrays.toString(data);
                for (byte b : data) {
                    queueAlarm.enQueue(b);
                }
                try {
                    for (int i = 0; i < 3; i++) {
                        queueAlarm.deQueue();
                    }
                    Double batt_vol = Double.valueOf(receive_one_field_alarm());//电源
                    System.out.println("  电源电压 ====================" + batt_vol);
                    String tx_high_vol = receive_one_field_alarm();//高压
                    String temperature1 = receive_one_field_alarm();//温度
                    String humidity1 = receive_one_field_alarm();//湿度
                    String alarm = receive_one_field_alarm();//告警
                    String outEle = receive_one_field_alarm();//外部电源
                    if (!msg.equals("")) {

                        System.out.println("  alarm ====================" + alarm);
                        alarmSta = true;
                        receive_one_field_sta = false;
                        recv_float_bool = false;
                        switch (alarm) {
                            case "2":
                                alarmVal = "RX接受的电压超最大量程范围";
                                break;
                            case "5":
                                alarmVal = "电池电压低";
                                break;
                            case "6":
                                alarmVal = "高压未达到预设值";
                                break;
                            case "7":
                                alarmVal = "用户主动紧急停止 或 TX电流超范围";
                                break;
                        }
                        //System.out.println("  alarm ====================" + alarm);
                        if (!alarm.equals("")) {
                            Message msg1 = new Message();
                            String msg2 = "设备告警！";
                            msg1.what = MSG_RECEIVE_ALARM;
                            msg1.obj = msg2;
                            mHandler.sendMessage(msg1);
                            Items items = findSelectItem();
                            String itemsId = items.getId().toString();
                            Sends sends = new Sends();
                            //sends.setItemId(Integer.valueOf(itemsId));
                            sends.setErrorPoint(String.valueOf(dtypelen0));
                            errorPointLine = csv_line_count;
                            sends.setErrorPointLine(errorPointLine);
                            //sends.setUid(simpleUUID);
                            Sends sends2 = new Sends();
                            sends2.setUid(simpleUUID);
                            sendsService.updade(sends, sends2);
                            List<Sends> sends1 = sendsService.getSends(sends);
                            alarmService = new AlarmService();
                            Alarm alarm1 = new Alarm();
                            alarm1.setAlarmMsg(send_piont + receive_piont + ":" + alarmVal);
                            alarm1.setSn(deviceId);
                            alarm1.setItemId(itemsId);
                            alarm1.setStatus(0);
                            alarm1.setSendId(String.valueOf(sends1.get(0).getId()));
                            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            Date date = new Date(System.currentTimeMillis());
                            alarm1.setCreateTime(sim.format(date));
                            alarm1.setUpdateTime(sim.format(date));
                            Alarm alarm2 = new Alarm();
                            alarm2.setSendId(String.valueOf(sends1.get(0).getId()));
                            alarmService.saveOrUpdade(alarm1,alarm2);
                            stopMyThread();
                            myThread.pauseThread();
                            socketUtils.isReConnect = true;
                            socketUtils.releaseSocket();
                            receive_one_field_sta = false;
                        }

                    }
                } catch (InterruptedException e) {
                    //throw new RuntimeException(e);
                    Log.e("alarm ", String.valueOf(e));
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
            }
        });
    }

    public synchronized String receive_one_field_alarm() throws InterruptedException, UnsupportedEncodingException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean bl = true;
        String msgbt = "";
        while (bl) {

            byte tmp = (byte) queueAlarm.deQueue();
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }
        if (one_field.size() > 0) {
            msgbt = socketUtils.recv_float_alarm(one_field);
        }

        return msgbt;
    }

    private boolean getStatus(String message) {
        Boolean stabool = false;
        if (message.contains("0,Success;") && !message.equals("")) {
            System.out.println("======================== Success bad_param ================" + message);
            stabool = true;
        } else if (message.contains("0,wait;")) {
            System.out.println("======================== wait bad_param ================" + message);
            stabool = false;
        } else if (message.contains("0,Timeout;")) {
            System.out.println("======================== bad_param ================" + message);
            System.out.println(" kSetMuxBoxConnect switch box connect error ");
            stabool = false;
            String msg1 = "开关盒子连接出错！";
            stopMyThread();
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } else if (message.equals("0,Bad_Param;") || message.equals("0,BadParam;")) {
            System.out.println("======================== bad_param ================" + message);
            stabool = false;
            String msg1 = "ABMN配置错误！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } else if (message.equals("0,alarm;")) {
            System.out.println("========================alarm bad_param ================" + message);
            stopMyThread();
            getAlarm18();
            stabool = false;
            String msg1 = "设备告警！";
            Message msg = new Message();
            msg.what = MSG_RECEIVE_TOAST_DATA;
            msg.obj = msg1;
            mHandler.sendMessage(msg);
        } else if (message.equals("None")) {
            System.out.println(" usb/wifi connect error ");
            stabool = false;
        } else if (message.contains("kErrorAlarm")) {//告警写入
            System.out.println(" kErrorAlarm================= " + message);
            Alarm alarm = new Alarm(itemsId);
            alarm.setAlarmMsg(message);
            alarmService.save(alarm);
            stabool = false;
        } else if (message.equals("null")) {
            if (startCount == 1) {
                stabool = false;
                String msg1 = "采集数据失败！";
                Message msg = new Message();
                msg.what = MSG_RECEIVE_TOAST_DATA;
                msg.obj = msg1;
                mHandler.sendMessage(msg);
            }
        }
        return stabool;
    }


    public void getTask() {
        //SocketMergeCallBackUtils.success_count = 6;
        byte[] data5 = pyobj1.callAttr("onKReSync", SocketMergeCallBackUtils.packet_indx).toJava(byte[].class);
        SocketMergeCallBackUtils.writeMsgByte(data5, new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient  17", "Text sent successfully ============= " + new String(data));
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Failed to send text: " + errorMessage);
            }
        });
        System.out.println(" 超时重复开始= " + DateUtils.parseYmdHmsDate());
    }


    class MyThread extends Thread {
        public final Object lock = new Object();
        public boolean threadExit;


        public MyThread() {
            threadExit = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        public void pauseThread() {
            threadExit = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        public void resumeThread() {
            threadExit = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        public void threadExit() {
            threadExit = true;
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        public void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            System.out.println("---------------dtypelen---" + dtypelen);
            System.out.println("---------------threadExit---" + threadExit);
            while (!threadExit) {
                //Log.i(TAG, "-------------------------run: socket " + socketUtils.socket);
                if (null != socketUtils.socket) {
                    if (null != senduId) {
                        dtypelen0 = Integer.parseInt(errorPoint);
                    }
                    msg_sueecss_count = 1;
                    //returnSta = false;
                    String abmnStr = "";
                    if (inclickGatherCount == 0) {
                        System.out.println("---------------dtypelen0---=" + 0);
                        dtypelenAbmn = 0;
                        if (null != senduId) {
                            abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, dtypelen0).toJava(String.class);
                        } else {
                            abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, 0).toJava(String.class);
                        }

                    } else {
                        System.out.println("---------------dtypelen0---=" + dtypelen0);
                        dtypelenAbmn = dtypelen0;
                        if (dtypelen0 == dtypelen) {

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //socketUtils.releaseSocket();//接收结束 关闭socket避免 超时操作
                                    myThread.pauseThread();
                                    Message msg = new Message();
                                    msg.what = MSG_RECEIVE_OVER_DATA;
                                    mHandler.sendMessage(msg);


//                                    Boolean boorMS = FileDownUtil.moveFile(DOWN_NAME + "RMS_" + saveCvsFileName, DOWN_NAME + fileName.replace(".cvs", "") + "/" + "RMS_" + saveCvsFileName, myContext);
//                                    //FileDownUtil.deleteFile(DOWN_NAME + saveCvsFileName);
//                                    Log.e("cvs移动到文件", "cvs移动到文件====================" + String.valueOf(boo));
                                }
                            }).start();
                            dtypelen = 0;

//                                pauseThread();
                            break;
                        } else if (dtypelen0 > dtypelen) {
                            return;
                        }
                        System.out.println("---------------subABMN---");
                        abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, dtypelen0).toJava(String.class);
                        if (dtypelen0 % boxId == 0) {
                            boxInx += 1;
                        }
                    }

                    if (abmnStr.length() > 0) {
                        if (devtype == 0 | devtype == 1) {
                            abmnlis = abmnStr.split(",");
                        } else {
                            String[] abmnliswn = abmnStr.split(",");
                            // 临时变量存储元素
                            String tempA = abmnliswn[0];
                            String tempB = abmnliswn[3];
                            String tempM = abmnliswn[1];
                            String tempN = abmnliswn[2];
                            if (null != senduId) {
                                abmnlis = new String[4];
                            } else if (null == abmnlis) {
                                abmnlis = new String[4];
                            }
                            abmnlis[0] = tempA;
                            abmnlis[1] = tempB;
                            abmnlis[2] = tempM;
                            abmnlis[3] = tempN;
                        }

                    }

                    //kSetTxWaveWithParam 3
//                    String abmbinx = "";
//                    if (boxInx == 0) {
//                        abmbinx = alis.get(0);
//                    } else {
//                        abmbinx = alis.get(boxInx);
//                    }
                    System.out.println("---------------onSendParamToMcu---");
                    data = pyobj1.callAttr("onSendParamToMcu", 1, send_frequency_value, packet_indx1, send_voltage_value).toJava(byte[].class);

                    //kClearAllMuxBoxConnect 15
                    if (boxlis.length > 0) {
                        data2 = pyobj1.callAttr("clear_mux", boxlis[0], boxlis[1], boxlis[2], boxlis[3], boxlis[4],
                                boxlis[5], boxlis[6], boxlis[7], boxlis[8], boxlis[9]).toJava(byte[].class);
                    }

                    //kSetMuxBoxConnect 2
                    String box = SwitchBoxUtil.boxIdToSpilt(alis, Integer.parseInt(abmnlis[0]));
                    String box2 = SwitchBoxUtil.boxIdToSpilt(alis, Integer.parseInt(abmnlis[1]));
                    String box3 = SwitchBoxUtil.boxIdToSpilt(alis, Integer.parseInt(abmnlis[2]));
                    String box4 = SwitchBoxUtil.boxIdToSpilt(alis, Integer.parseInt(abmnlis[3]));
                    Arrange arrange = new Arrange();
                    arrange.setItemId(Integer.valueOf(itemsId));
                    List<Arrange> arrangeLis = arrangeService.getArrange(arrange);

                    if (arrangeLis.size() > 0) {
                        model = arrangeLis.get(0).getDeviceType();
                    }
                    data3 = pyobj1.callAttr("update_poles_connect", box, box2,
                            box3, box4, model).toJava(byte[].class);
                    send_piont = "A" + box.replace(",", ":") + "; " + "B" + box2.replace(",", ":");
                    receive_piont = "M" + box3.replace(",", ":") + "; " + "N" + box4.replace(",", ":");
                    loding_count = 1;
                    send_poiont_val.setText(send_piont);
                    receive_poiont_val.setText(receive_piont);
                    try {
                        if (!startGater) {
                            Thread.sleep(1);
                            //pauseThread();
                            if (socketUtils.socketReconnection) {
                                socketUtils.socketReconnection = false;
                                recv_float_bool = false;
                            } else {
                                System.out.println("---------------socketListener00000000---");

                                Boolean socketListenerBoo = socketListener();


                                System.out.println("---------------socketListener---  " + socketListenerBoo);
                                if (socketListenerBoo) {
                                    myBool = false;
                                    myBool2 = false;
                                    myBool3 = false;
                                    myBool4 = false;
                                    myBool5 = false;
                                    errorSta = false;
                                    if(alarmSta){
                                        recv_float_bool = false;
                                    }else {
                                        recv_float_bool = true;
                                    }

                                    returnSta = recv_float_array_with_indx(abmnlis);
//                                    senduId = null;
                                    Log.e("returnSta", "----------returnSta=-------------" + returnSta);
                                    if (returnSta) {
                                        dtypelen0 += 1;
                                        startCount = 0;
                                        inclickGatherCount += 1;
                                        abmn_indx += 1;
                                        receiveDataAll = "";
                                        packet_indx = 0;
                                        packet_lens = 0;
                                        packet_lens_old = 0;
                                        // resumeThread();
                                    } else {
//                                        if(dtypelen0!=0){
//                                            dtypelen0 -= 1;
//                                        }
                                        socketUtils.socketReconnection = false;
                                        rec_count = 0;
                                        rx_voltage_data1 = new StringBuffer();
                                        tx_c_rx_v_lis = new ArrayList<>();
                                        tx_c_rx_v_lis.clear();
                                        //VIRO_part.clear();
                                        //VIRO.clear();
                                        tx_current_data1 = new StringBuffer();
                                        rx_voltage_data_all1 = new StringBuffer();
                                        recv_float_bool = true;
                                        returnSta = true;
                                        receive_one_field_sta = true;
                                        boolErr = true;
                                        anewSta = true;
                                        reconnectionCount += 1;
                                        queueMsg.clear();
                                        //stopMyThread();
//                                        if (reconnectionCount > 10) {
//                                            myThread.pauseThread();
//                                            Message msg = new Message();
//                                            msg.what = MSG_RECEIVE_FAIL_DATA;
//                                            mHandler.sendMessage(msg);
//                                        }
                                        Log.e("recvFalse", "----------returnSta=False-------------");
                                        socketUtils.clrearBuffer();
                                        Thread.sleep(1000);
//                                        socketUtils.clrearBuffer();
//                                        Thread.sleep(500);
//                                        socketUtils.clrearBuffer();
//                                        Thread.sleep(500);
                                    }
//
                                } else {
                                    System.out.println("---------------socketListener false---  ");
                                    Thread.sleep(1000);
                                    socketUtils.isReConnect = true;
                                    socketUtils.releaseSocketNew();
                                    startMyThread();
                                    queueMsg.clear();
//                                    if(dtypelen0!=0){
//                                        dtypelen0 -= 1;
//                                    }
                                    socketUtils.socketReconnection = false;
                                }
                            }


                        }

                    } catch (InterruptedException e) {
                        //throw new RuntimeException(e);
                        Log.e("InterruptedException", e.toString());
                    } catch (IOException e) {
                        //throw new RuntimeException(e);
                        Log.e("IOException", e.toString());
                    }

                    rec_count_s = 0;
                    continue;
                }
            }

        }
    }

    private void startMyThread() {
        recv_float_bool = true;
        returnSta = true;
        receive_one_field_sta = true;
        boolErr = true;
    }

    private void stopMyThread() {
        recv_float_bool = false;
        returnSta = false;
        receive_one_field_sta = false;
        boolErr = false;
    }

    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        pyobj = py.getModule("ERT_Plot");
        //调用hello_python.py里面的plot函式
        pyobj1 = py.getModule("Send_Param");
        pyobj2 = py.getModule("fft_ui");
        pyobjfft = py.getModule("fft_ui");
    }

    private Boolean getViewInit() {
        no_data_img = findViewById(R.id.no_data_img);
        title_back = findViewById(R.id.gather_title_back);
//        stop_gather = findViewById(R.id.stop_gather);
        start_gather = findViewById(R.id.start_gather);
//        plan_break_char = findViewById(R.id.plan_break_char);
//        arrange_char = findViewById(R.id.arrange_char);
        img = findViewById(R.id.imageViews);

        plan_break = findViewById(R.id.plan_break);
        permutations = findViewById(R.id.permutations);
        waveform = findViewById(R.id.waveform);
        frequency_spectrum = findViewById(R.id.frequency_spectrum);

        device_type_val = findViewById(R.id.device_type_val);
        send_frequency_val = findViewById(R.id.send_frequency_val);
        receive_voltage_val = findViewById(R.id.receive_voltage_val);
        send_poiont_val = findViewById(R.id.send_poiont_val);
        receive_poiont_val = findViewById(R.id.receive_poiont_val);
        filter_type_val = findViewById(R.id.filter_type_val);
        Sends sends = getSend();
        if (sends != null) {
            freq_Indx = freqData[Integer.parseInt(sends.getSendFrequency())];
            device_type_val.setText(modeData[sends.getType()]);
            send_frequency_val.setText(freq_Indx + "hz");
            receive_voltage_val.setText(valtageData[Integer.parseInt(sends.getVoltage())] + "v");
            repeatUnm = repeatData[Integer.parseInt(sends.getRepeatNum())];
            filter = Integer.parseInt(sends.getFilterFrequency());
            filter_type_val.setText(freqFilterData[filter]);
        } else {
            Toast.makeText(this, "请先完成发射接收！", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private Sends getSend() {
        sendsService = new SendsService();
        itemsService = new ItemsService();
        Items items = new Items();
        items.setStatus(1);
        List<Sends> sends = null;
        try {
            List<Items> items1 = itemsService.getItems(items);
            if (items1.size() > 0) {
                sends = sendsService.getSends(new Sends(items1.get(0).getId()));
                if (sends.size() > 0) {
                    return sends.get(0);
                }
            } else {
                Toast.makeText(this, "请先创建项目！", Toast.LENGTH_SHORT).show();
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }



    private void initService() {
        boxOneService = new BoxOneService();
        boxTwoService = new BoxTwoService();
        boxThreeService = new BoxThreeService();
        boxFourService = new BoxFourService();
        boxFiveService = new BoxFiveService();
        boxSixService = new BoxSixService();
        boxSevenService = new BoxSevenService();
        boxEightService = new BoxEightService();
        boxNineService = new BoxNineService();
        boxTenService = new BoxTenService();
        Items items = findSelectItem();
        itemsId = items.getId().toString();
        //boxLatLon
        List<String> lisBoxOne = performJoinQuery(itemsId, "tb_boxOne");
        List<String> lisBoxTwo = performJoinQuery(itemsId, "tb_boxTwo");
        List<String> lisBoxThree = performJoinQuery(itemsId, "tb_boxThree");
        List<String> lisBoxFour = performJoinQuery(itemsId, "tb_boxFour");
        List<String> lisBoxFive = performJoinQuery(itemsId, "tb_boxFive");
        List<String> lisBoxSix = performJoinQuery(itemsId, "tb_boxSix");
        List<String> lisBoxSeven = performJoinQuery(itemsId, "tb_boxSeven");
        List<String> lisBoxEight = performJoinQuery(itemsId, "tb_boxEight");
        List<String> lisBoxNine = performJoinQuery(itemsId, "tb_boxNine");
        List<String> lisBoxTen = performJoinQuery(itemsId, "tb_boxTen");
        if (lisBoxOne.size() > 0) {
            boxLatLon = new ArrayList<>();
            String[] str = lisBoxOne.toArray(new String[0]);
            for (String item : str) {
                boxLatLon.add(item);
            }
        }
    }

    private List<String> performJoinQuery(String itemId, String tabName) {
        Items items = findSelectItem();
        String itemsId = items.getId().toString();
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // SQL语句：查询用户表和订单表，根据用户ID关联
        Cursor cursor = db.rawQuery("select box_one_lat,box_two_lat,box_three_lat,box_four_lat,box_five_lat,box_six_lat,box_seven_lat,box_eight_lat,box_nine_lat,box_ten_lat,box_eleven_lat,box_twelve_lat" +
                " from " + tabName + " where item_id = ? ", new String[]{itemId});
        System.out.println(cursor.getCount());
        List<String> lis = new ArrayList<>();
        // 遍历结果集
        while (cursor.moveToNext()) {
            String box_one_lat = cursor.getString(0);
            String box_two_lat = cursor.getString(1);
            String box_three_lat = cursor.getString(2);
            String box_four_lat = cursor.getString(3);
            String box_five_lat = cursor.getString(4);
            String box_six_lat = cursor.getString(5);
            String box_seven_lat = cursor.getString(6);
            String box_eight_lat = cursor.getString(7);
            String box_nine_lat = cursor.getString(8);
            String box_ten_lat = cursor.getString(9);
            String box_eleven_lat = cursor.getString(10);
            String box_twelve_lat = cursor.getString(11);
            lis.add(box_one_lat);
            lis.add(box_two_lat);
            lis.add(box_three_lat);
            lis.add(box_four_lat);
            lis.add(box_five_lat);
            lis.add(box_six_lat);
            lis.add(box_seven_lat);
            lis.add(box_eight_lat);
            lis.add(box_nine_lat);
            lis.add(box_ten_lat);
            lis.add(box_eleven_lat);
            lis.add(box_twelve_lat);

            // 处理查询结果
            // ...
        }

        cursor.close();
        db.close();
        return lis;
    }


    public void saveSends(Sends send) {
        Sends sends = new Sends();
        sends.setVoltage(send.getVoltage());
        sends.setType(1);
        sends.setStatus(0);
        sends.setErrorPoint("0");
        sends.setErrorPointLine(0);
        sends.setUid(simpleUUID);
        //sends.setElectricity(String.valueOf(send_electric_val.getText()));
        sends.setRepeatNum(send.getRepeatNum());
        sends.setSendFrequency(send.getSendFrequency());
        sends.setSendDuration(send.getSendDuration());
        sends.setItemId(send.getItemId());
        //sends.setBoxaddr(send.getBoxaddr());
        sends.setSn(sn);
        sends.setFilterFrequency(send.getFilterFrequency());
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        sends.setCreateTime(sim.format(date));
        sends.setUpdateTime(sim.format(date));
        sendsService = new SendsService();
        boolean bl = sendsService.save(sends);
        //String simpleUUID = IdUtil.simpleUUID();
        fileName = FileDownUtil.getFileName(simpleUUID);
        if (bl) {
            System.out.println("采集数据保存成功！");
        }
        if (inclickGatherCount == 0) {
            Thread.State state = myThread.getState();
            System.out.println(state);
            myThread = null;
            if (null != myThread) {

                try {
                    myThread.interrupt();

                    Thread.sleep(10);
                    myThread.start();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            myThread = new MyThread();
            myThread.start();

        } else {
            inclickGatherCount = 0;
            myThread.resumeThread();
            returnSta = true;
        }
    }

    public Boolean sendMcu(Sends sends, Integer itemId) {
        sf = Integer.parseInt(sends.getSendFrequency()) + 1;
        srepeat = Integer.parseInt(repeatData[Integer.parseInt(sends.getRepeatNum())]);
        svaltage = Integer.parseInt(valtageData[Integer.parseInt(sends.getVoltage())]);
        send_frequency_value = String.valueOf(sf);
        send_repeat_value = String.valueOf(srepeat);
        send_voltage_value = String.valueOf(svaltage);
        //clearStrLisAll = sends.getBoxaddr().split(",");
        packet_indx1 = Integer.parseInt(String.valueOf(send_repeat_value));
        packet_indx = packet_indx1;
        sf = Integer.parseInt(sends.getSendFrequency());
        int send_repeat = Integer.parseInt(send_repeat_value);
        repate_indx = new int[send_repeat];
        for (int i = 0; i < send_repeat; i++) {
            repate_indx[i] = i;
        }
        Arrange arrange1 = new Arrange();
        arrange1.setItemId(itemId);
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
        //Integer ns = 0;

        if (arrangeLis.size() == 0) {
            Toast.makeText(this, "请先添加排列设计！", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            //ns = arrangeLis.get(0).getDeviceTypeLen();
            dtype = arrangeLis.get(0).getDtype();
            dtypelen = arrangeLis.get(0).getDeviceTypeLen();
            shape = arrangeLis.get(0).getShape();
            abmn = arrangeLis.get(0).getDeviceTypeVal();
            devtype = arrangeLis.get(0).getDeviceType();
            permutationMode = modeData[devtype];//添加采集模式
            //dtypelen0 = dtypelen;
        }
        // myThread.start();
        return true;
    }

    private synchronized Boolean recv_float_array_with_indx(String[] abmnlis) throws InterruptedException, IOException {

        int status = 0;
        int error = 0;
        int bak_packet_lens = 0;
        int bak_indx = 0;
        int re_indx = 0;
        returnSta = false;
        // recv_float_bool = true;
        Double[] cv_lis = null;
        jbA = new JSONArray();
        JSONObject jb = null;
        tx_c_rx_v_lis = new ArrayList<Double[]>();

        while (recv_float_bool) {
            //VIRO_part = new ArrayList<BigDecimal>();
            cv_lis = new Double[2];

            bak_packet_lens = packet_lens_old / 3;
            error = 0;
            String headStr = "";
            if (socketUtils.socketReconnection) {
                Log.e("socketReconnection", "-------------socketReconnection00000-----------");
                return false;

                //socketUtils.clrearBuffer();
            }

            //接收包头AA55
            receive_one_field_sta = true;
            byte[] str_one_field = receive_one_field("AA55");
//            if(str_one_field.length == 0){
//                break;
//            }
            int str_one_field_len = str_one_field.length;
            headStr = Arrays.toString(str_one_field);

            if (str_one_field_len > 0) {
                if (str_one_field[0] == 0) {
                    System.out.println("header len == 0" + str_one_field + " --- " + Arrays.toString(str_one_field));
                    break;

                } else if (str_one_field_len < 2) {
                    System.out.println("header len < 2" + str_one_field + " --- " + Arrays.toString(str_one_field));
                    error += 1;
                    break;

                } else if (str_one_field_len > 2) {
                    error = error + 1;
                    System.out.println("header len >2, break: " + str_one_field + " --- " + Arrays.toString(str_one_field));
                    break;


                } else {
                    int header = recv_unsigned_int(str_one_field);
                    if (header != 0xAA55) {
                        System.out.println("header error " + new String(str_one_field) + " --- " + Arrays.toString(str_one_field));

                    }
                }
            }else {
                //`break;
            }


            //接收包的indx
            //需要对接收到的_receive_one_field的长度做判断，如果长度不够，就认为接收出错
            String indexStr = "";
            int indx = 0;

            receive_one_field_sta = true;
            byte[] str_one_field2 = receive_one_field("indx");
//            if(str_one_field2.length == 0){
//                break;
//            }
            int str_one_field2_len = str_one_field2.length;
            indexStr = Arrays.toString(str_one_field2);
            //System.out.println("--------------------str_one_field2--------------------" + str_one_field2);

            if (str_one_field2_len > 0) {
                //int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field2);
                if (str_one_field2_len != 2) {
                    error = error + 1;
                    System.out.println("header no error 0--- " + headStr);
                    //System.out.println("index no error 0--- " + indexStr);
                    System.out.println("接收包的indx error1 " + new String(str_one_field2) + " --- " + Arrays.toString(str_one_field2));
                    break;
                } else {
                    indx = recv_unsigned_int(str_one_field2);
                    //System.out.println("--------------------index new --------------------  " + indx);
                    //System.out.println("indx" + Arrays.toString(str_one_field2));
                    if (indx == 43605) {
                        //System.out.println("接收包的indx 出错  " + indx);
                    }
                    if (errorSta) {
                        //System.out.println("接收包的indx 出错  " + indx);
                    } else {
                        if (indx == 1) {
                            //System.out.println("--------------------index new --------------------  " + indx);

                        }
                    }
                    errorSta = false;

                    if (indx > bak_packet_lens) {
                        error = error + 1;
                        //break;
                        System.out.println("header no error 0--- " + headStr);
                        //System.out.println("index no error 0--- " + indexStr);
                        System.out.println("接收包的indx111 出错  " + indx + " bak_packet_lens= " + bak_packet_lens);
                        break;
                    }

                }
            }else {
                //break;
            }


            //tx_voltage_data
            String txvStr = "";
            String tx_voltage1 = null;
            int tx_voltage1_len = 0;
            Double tx_voltage2 = null;
            receive_one_field_sta = true;

            byte[] str_one_field3 = receive_one_field("tx_voltage_data");
//            if(str_one_field3.length == 0){
//                break;
//            }
            int str_one_field3_len = str_one_field3.length;

            txvStr = Arrays.toString(str_one_field3);
            //System.out.println("--------------------str_one_field3--------------------" + str_one_field3);

            //String tx_voltage1 = null;
            if (str_one_field3_len > 0) {
                tx_voltage1_len = str_one_field3_len;
                // int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field3);
                if (str_one_field3_len != 4) {
                    error = error + 1;
                    //break;
                    System.out.println("header no error 0--- " + headStr);
                    // System.out.println("index no error 0--- " + indexStr);
                    System.out.println("tx_voltage_data error1 " + new String(str_one_field3) + " --- " + Arrays.toString(str_one_field3));
                    break;
                } else {
                    tx_voltage1 = recv_float(str_one_field3);
                    if (!tx_voltage1.equals("")) {
                        BigDecimal bd = stringToDouble(tx_voltage1).multiply(BigDecimal.valueOf(100));
                        tx_voltage2 = bd.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                        //System.out.println(" --------------------tx_voltage1-------------------- " + bd);

                        errorSta = false;
                    }

                }
            }else {
                //break;
            }


            //tx_current_data
            String txcStr = "";
            int tx_current1_len = 0;
            String tx_current1 = null;
            Double tx_current2 = null;
            BigDecimal tx_current3 = null;

            receive_one_field_sta = true;
            byte[] str_one_field4 = receive_one_field("tx_current_data");
//            if(str_one_field4.length == 0){
//                break;
//            }
            int str_one_field4_len = str_one_field4.length;
            txcStr = Arrays.toString(str_one_field4);
            //System.out.println("--------------------str_one_field4--------------------" + str_one_field4);

            if (str_one_field4_len > 0) {
                tx_current1_len = str_one_field4_len;
                //int str_lens = dataParseUtil.entiretyDecodeStructByteBack(str_one_field4);
                if (str_one_field4_len != 4) {
                    error = error + 1;
                    System.out.println("tx_v no error 0--- " + txvStr);
                    System.out.println("tx_current_data error1 " + new String(str_one_field4) + " --- " + Arrays.toString(str_one_field4));
                    break;
                } else {
                    tx_current1 = recv_float(str_one_field4);
                    if (!tx_current1.equals("")) {
                        BigDecimal bd = stringToDouble(tx_current1).multiply(BigDecimal.valueOf(1000));
                        cv_lis[0] = Double.valueOf(String.valueOf(bd.abs().setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));
                        tx_current2 = bd.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();

                    }

                }
            }else {
                //break;
            }


            //rx_voltage_data
            String rxvStr = "";
            int rx_voltage1_len = 0;
            String rx_voltage1 = null;
            Double rx_voltage2 = null;
            BigDecimal rx_voltage3 = null;

            int indx_end = 0;
            receive_one_field_sta = true;
            byte[] str_one_field5 = receive_one_field("rx_voltage_data");
//            if(str_one_field5.length == 0){
//                break;
//            }
            int str_one_field5_len = str_one_field5.length;
            if (str_one_field5_len > 0) {
                rx_voltage1_len = str_one_field5_len;
                if (str_one_field5_len != 4) {
                    error = error + 1;
                    System.out.println("rx_voltage1_len ！= 4 " + rxvStr);
                    break;
                } else {
                    rx_voltage1 = recv_float(str_one_field5);
                    if (!rx_voltage1.equals("")) {
                        BigDecimal bd = stringToDouble(rx_voltage1).multiply(BigDecimal.valueOf(1000));
                        cv_lis[1] = Double.valueOf(String.valueOf(bd.abs().setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue()));

                        rx_voltage_data1.append(bd.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue() + ", ");
                        rx_voltage2 = bd.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
//                            rx_voltage3 = bd.abs().setScale(5, BigDecimal.ROUND_HALF_UP);
                        //VIRO_part.add(BigDecimal.valueOf(rx_voltage2));

                    }
                }
            }else {
                //break;
            }

//            if (!"".equals(rx_voltage1) && !"".equals(tx_current1)) {//极化率
//                if (rx_voltage1_len == 4 && tx_current1_len == 4) {//过滤到出错的数据
//                    String polarizability = pyobjfft.callAttr("polarizability", rx_voltage1, tx_current1).toJava(String.class);
//                    queueMsg.enQueue(polarizability + ", ");
//                    queueMsg.enQueue(permutationMode + ";");
//                }
//
//            }
//            if (!"".equals(rx_voltage1) && !"".equals(tx_voltage1)) {//极化率
//                if (rx_voltage1_len == 4 && tx_voltage1_len == 4) {//过滤到出错的数据
//                    String polarizability = pyobjfft.callAttr("polarizability", tx_voltage1, rx_voltage1).toJava(String.class);
//                    //Log.d("polarizability", "--------------------polarizability-------------------- " + polarizability);
//                    queueMsg.enQueue(polarizability + ", ");
//                    queueMsg.enQueue(permutationMode + ";");
//                }
//
//            }
//            if (!"".equals(rx_voltage1) && !"".equals(tx_voltage1)) {//原始数据中的极化率
//                if (rx_voltage1_len == 4 && tx_voltage1_len == 4) {//过滤到出错的数据
//
//                    resistivityVal = getResistivity(Integer.parseInt(abmnlis[0]), Integer.parseInt(abmnlis[1]),
//                            Integer.parseInt(abmnlis[2]), Integer.parseInt(abmnlis[3]), rx_voltage3, tx_current3);
//                    VIRO_part.add(resistivityVal);
//                    VIRO_part.add(kVal);
//                    //System.out.println("kVal ======= "+kVal);
//                    queueMsg.enQueue(resistivityVal + ", ");
//                    queueMsg.enQueue(permutationMode + ";");
//                    kVal = null;
//                }
//
//            }
            // VIRO.add(VIRO_part);

            if (error == 0) {
                queueMsg.enQueue(ContextVariable.freq + ", ");
                queueMsg.enQueue(packet_indx_old + ", ");
                queueMsg.enQueue(indx + ", ");
                queueMsg.enQueue(abmnlis[0] + ", ");
                queueMsg.enQueue(abmnlis[1] + ", ");
                queueMsg.enQueue(abmnlis[2] + ", ");
                queueMsg.enQueue(abmnlis[3] + ", ");
                queueMsg.enQueue(tx_voltage2 + ", ");
                queueMsg.enQueue(tx_current2 + ", ");
                queueMsg.enQueue(rx_voltage2 + ", ");
                queueMsg.enQueue(0 + ", ");
                queueMsg.enQueue(permutationMode + ";");
                rec_count = rec_count + 1;

                packet_lens -= 3;
                tx_c_rx_v_lis.add(cv_lis);
                if (packet_lens <= 0) {
                    Log.e("bak_packet_lens & rec_count", packet_lens + " ---- " + rec_count);
                    socketUtils.clrearBufferNew();
                    if (bak_packet_lens == rec_count) {

                        try {
                            ArrayList<Double[]> tx_c_rx_v_lis_all = new ArrayList<>();
                            tx_c_rx_v_lis_all.addAll(tx_c_rx_v_lis);
                            jb = new JSONObject();
                            //直接在 list对象填充到json对象之前定义这行就行了 没作用
                            //JSON.toJSONString(tx_c_rx_v_lis, SerializerFeature.DisableCircularReferenceDetect);
                            jb.put(String.valueOf(repate_indx[re_indx]), tx_c_rx_v_lis_all);
                            if (Integer.parseInt(repeatUnm) > 1) {
                                re_indx += 1;
                            }

                            jb_tu.putAll(jb);
                            tx_c_rx_v_lis.clear();

                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                        System.out.println(" =============== 4,start; 结束= " + DateUtils.parseYmdHmsDate());
                        //System.out.println(rx_voltage_data);
                        recv_float_bool = false;
                        receive_one_field_sta = false;

                        if (socketUtils.socket.isClosed() == true && socketUtils.socket.isConnected() == false) {
                            socketUtils.releaseSocketNew();
                            rx_voltage_data1 = new StringBuffer();
                            tx_current_data1 = new StringBuffer();
                            rx_voltage_data_all1 = new StringBuffer();
                        }

                        anewSta = true;
                        byte[] data4 = pyobj1.callAttr("onKConfirmToMcu", rec_count).toJava(byte[].class);
                        ////////////////////////////////////////////////////

                        if (packet_indx > 0) {
                            packet_indx_111 = 1;
                            Log.e("SocketClient", " ---------------------- packet_indx>0 ----------------------------");
                            Log.e("SocketClient", " ----------------------reconnectionCount---------------------------- " + reconnectionCount);
                            // socketUtils.clrearBuffer();
                            SocketMergeCallBackUtils.writeMsgByte(data4, new Callback() {
                                byte[] byAll = null;

                                @Override
                                public void onSuccess(byte[] data) {
                                    System.out.println(" =============== 4,start data  == " + Arrays.toString(data) + " len= " + data.length);

                                    if (data.length > 0) {

                                        System.out.println(" =============== 4,start;2222222 结束= ------------------ data == " + Arrays.toString(data) + " len= " + data.length);

                                        if (data[data.length - 1] != 59) {
                                            Boolean bool = true;
                                            byte[] bylist = new byte[1];
                                            while (bool) {
                                                byte buf = SocketMergeCallBackUtils.read()[0];
                                                bylist[0] = buf;
                                                byte[] bytes1 = (byte[]) ArrayUtils.toPrimitive(bylist);
                                                byAll = ArrayUtil.byteMerger(data, bytes1);
                                                System.out.println(" 4 ------------------ alldata == " + Arrays.toString(byAll));
                                                myBool = ReceiveDataForAnalyze1(byAll);
//                                                if(!myBool){
//                                                    stopMyThread();
//                                                    break;
//                                                }
                                                bool = false;
                                                break;
                                            }
                                        } else {
                                            myBool = ReceiveDataForAnalyze1(data);
//                                            if(!myBool){
//                                                stopMyThread();
//                                                return;
//                                            }
                                        }

                                        Log.i("SocketClient", "Text sent successfully ============= " + Arrays.toString(byAll));
                                        Log.i("SocketClient", "packet_indx ============= " + packet_indx);

                                        anewSta = true;
                                        System.out.println(" 重复开始1111= " + DateUtils.parseYmdHmsDate());
                                        System.out.println("------------ bytecount 16 ==============" + socketUtils.bytecount);
                                        socketUtils.bytecount = 0;
                                        socketUtils.reconnection = 0;

                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                saveCvs();
                                            }
                                        }).start();


                                        recv_float_bool = true;
                                        receive_one_field_sta = true;

                                        //System.out.println(" 点击结束= " + DateUtils.parseYmdHmsDate());
                                        rec_count_s = rec_count;
                                        rec_count = 0;
                                        back_over = true;
                                        receive_packet_indx_count += 1;
                                        rx_voltage_data_all1.append(rx_voltage_data1.toString() + ";");
                                        packet_indx -= 1;
                                        System.out.println("------------ bytecount 16 结束==============");
                                    } else {
                                        bo1 = false;
                                    }

                                }

                                @Override
                                public void onFailure(String errorMessage) {
                                    Log.e("SocketClient", "Failed to send text: " + errorMessage);
                                }
                            });
                            Log.e("writeMsgByte16", "writeMsgByte16 Failed to send text ==== " + bo1);
                            if (!bo1) {
                                bo1 = true;
                                return false;
                            }
                        } else {
                            Log.e("SocketClient", " ---------------------- packet_indx==1 ----------------------------");
                            Log.e("SocketClient", " ----------------------reconnectionCount---------------------------- " + reconnectionCount);
                            SocketMergeCallBackUtils.writeMsgByte(data4);

                            anewSta = true;
                            System.out.println(" 重复开始2222= " + DateUtils.parseYmdHmsDate());
                            System.out.println("------------ bytecount ==============" + socketUtils.bytecount);
                            socketUtils.bytecount = 0;

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    saveCvs();
                                    //saveRmsCvs();
                                    //VIRO.clear();
                                }
                            }).start();

                            recv_float_bool = true;
                            receive_one_field_sta = true;

                            //System.out.println(" 点击结束= " + DateUtils.parseYmdHmsDate());
                            rec_count_s = rec_count;
                            rec_count = 0;
                            back_over = true;
                            receive_packet_indx_count += 1;
                            rx_voltage_data_all1.append(rx_voltage_data1.toString() + ";");
                            if (packet_indx == 0) {
                                String[] rxStrList = rx_voltage_data_all1.toString().split(";");
                                String rx_voltage_data_add = ArrayUtil.strToStrArrrayAdd(rxStrList);//将string[] 做叠加处理
                                rx_voltage_data_len = rx_voltage_data_add.substring(0, rx_voltage_data_add.length() - 1).split(",").length;
                                if (!rx_voltage_data_add.equals("")) {
                                    if (error_jb_tu != 0) {
                                        for (int i = 0; i < error_jb_tu; i++) {
                                            jb_tu.putAll(jb);
                                        }
                                        error_jb_tu = 0;
                                    }
                                    jb_tu_str = jb_tu.toString();
                                    jsonObjectMsg = initJson();
                                    if (gatherType == 1) {
                                        Message msg = new Message();
                                        msg.what = MSG_RECEIVE_TU_DATA;
                                        msg.arg1 = dtypelenAbmn;
                                        msg.obj = rx_voltage_data_add;
                                        mHandler.sendMessage(msg);
                                    } else if (gatherType == 2) {
                                        Message msg = new Message();
                                        msg.what = MSG_RECEIVE_PAI_DATA;
                                        msg.arg1 = dtypelenAbmn;
                                        msg.obj = rx_voltage_data_add;
                                        mHandler.sendMessage(msg);
                                    } else if (gatherType == 3) {
                                        Message msg = new Message();
                                        msg.what = MSG_RECEIVE_BO_DATA;
                                        msg.arg1 = dtypelenAbmn;
                                        msg.obj = rx_voltage_data_add;
                                        mHandler.sendMessage(msg);
                                    } else if (gatherType == 4) {
                                        Message msg = new Message();
                                        msg.what = MSG_RECEIVE_PIN_DATA;
                                        msg.arg1 = dtypelenAbmn;
                                        msg.obj = rx_voltage_data_add;
                                        mHandler.sendMessage(msg);
                                    }

                                    cv_lis = null;
                                }
                                rx_voltage_data1 = new StringBuffer();
                                tx_current_data1 = new StringBuffer();
                                rx_voltage_data_all1 = new StringBuffer();
                                returnSta = true;
                                socketUtils.reconnection = 0;
                                System.out.println("---------------------重复开始 break 111------------");
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                                break;
                            }
                            //返回正确确认包，
                            rec_count = 0;
                        }

                    } else {
                        status = 1;
                        Log.e("oneOver", "--------------oneOverHandle-------------------");
                        errorHandle(indx);
                    }
                }
            } else if (packet_lens > 0 && indx == 1) {
                //数据丢包处理，index =1 重新发送命令
                //errorHandle(indx);
                Log.e("oneOver", "--------------packet_lens > 0 && indx == 1-------------------");
                break;
            }
            //Log.e("1616161616161616161616", "-------------1616161616161616161616-----------");
            if (socketUtils.socketReconnection) {
                Log.e("socketReconnection", "-------------socketReconnection-----------");
                break;
            }

        }
        return returnSta;
    }

    private synchronized byte[] receive_one_field(String name) throws InterruptedException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        while (receive_one_field_sta) {
//            if(alarmSta){
//                return new byte[0];
//            }
            byte[] tmp1 = socketUtils.read();

            if(tmp1.length>1){
                break;
            }
            byte tmp = tmp1[0];
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
//                    if(tmp == 59){
//                        SocketMergeCallBackUtils.count59 += 1;
//                    }
                } else {
                    //one_field.add((byte) 47);
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                }
                else {
                    one_field.add(tmp);
                }
            }
        }
        byte[] bytes = ArrayUtil.listTobyte(one_field);
        receive_one_field_sta = false;
        //Log.e("receive_one_field", Arrays.toString(bytes));
        return bytes;
    }


    private void errorHandle(Integer indx) throws InterruptedException {
        System.out.println("------------ bytecount error ==============" + socketUtils.bytecount + "--" + packet_lens + "--" + indx);
        socketUtils.bytecount = 0;
        rx_voltage_data1 = new StringBuffer();
        tx_current_data1 = new StringBuffer();
        rx_voltage_data_all1 = new StringBuffer();
        errorSta = false;
        headSta = false;
        indxSta = false;
        txvSta = false;
        txcSta = false;
        rxvSta = false;
        errorCount = false;
        anewSta = false;
        error = 0;
        returnSta = false;
        rec_count = 0;
        packet_lens = packet_lens_old;
        //SocketMergeCallBackUtils.packet_lens=0;
        queueMsg.clear();
        Thread.sleep(1000);
        try {
            socketUtils.clrearBuffer();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        byte[] data4 = pyobj1.callAttr("onKReSync", packet_indx).toJava(byte[].class);//b'17,\x04/\x00;'
        SocketMergeCallBackUtils.writeMsgByte(data4, new Callback() {
            @Override
            public void onSuccess(byte[] data) throws IOException {
                Log.i("SocketClient", "Text sent successfully 17============= " + new String(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    Boolean bl1 = getStatus(msg);
                    if (bl1) {
                        Boolean bool = true;
                        List<Byte> bylist = new ArrayList<Byte>();
                        while (bool) {
                            byte buf = SocketMergeCallBackUtils.read()[0];
                            Log.e("SocketClient 17", "Text sent successfully 17 byte ============= " + buf);

                            if (buf != 59) {
                                bylist.add(buf);
                                if (bylist.size() > 1) {
                                    if (bylist.get(0) == bylist.get(1)) {
                                        if (bylist.get(0) == 0) {
                                            bool = false;
                                            break;
                                        }
                                    }
                                }

                            } else {
                                bylist.add(buf);
                                byte[] bytes = ArrayUtil.listTobyte(bylist);
                                Boolean myBool = ReceiveDataForAnalyze1(bytes);
                                bool = false;
                                break;
                            }
                        }
                    } else {
                        Log.i("SocketClient", "Text sent successfully 17 222 ============= " + new String(data));
                        socketUtils.clrearBuffer();
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Failed to send text 17: " + errorMessage);
            }
        });
        //System.out.println(" 数据丢包，重复开始= " + DateUtils.parseYmdHmsDate());
        Log.e(" error  ", "------数据丢包，重复开始-----" + DateUtils.parseYmdHmsDate());
    }


    private Integer recv_unsigned_int(byte[] val) {

        return dataParseUtil.recv_unsigned_int(val);
    }

    private String recv_float(byte[] val) {
        return dataParseUtil.recv_float(val);
    }


    public void displayChart() {
        mChart1.setVisibility(View.GONE);
        mChart2.setVisibility(View.GONE);
        mChart3.setVisibility(View.GONE);
        mChart4.setVisibility(View.GONE);
    }

    public void onClick(View v) {
        displayChart();
        switch (v.getId()) {
            case R.id.plan_break:
                gatherType = 1;
                planBreak();
                break;
            case R.id.permutations:
                gatherType = 2;
                permutations();
                break;
            case R.id.waveform:
                gatherType = 3;
                waveform();
                break;
            case R.id.frequency_spectrum:
                gatherType = 4;
                frequencySpectrum();
                break;
            default:
                break;
        }

    }

    private void planBreak() {
        no_data_img.setVisibility(View.GONE);

        img.setVisibility(View.VISIBLE);
        mChart1.setVisibility(View.VISIBLE);
        mChart2.setVisibility(View.GONE);
        mChart3.setVisibility(View.GONE);
        mChart4.setVisibility(View.GONE);
        plan_break.setTextColor(Color.parseColor("#FF007AFF"));
        permutations.setTextColor(Color.parseColor("#A6000000"));
        waveform.setTextColor(Color.parseColor("#A6000000"));
        frequency_spectrum.setTextColor(Color.parseColor("#A6000000"));
        plan_break.setTextSize(18);
        permutations.setTextSize(16);
        waveform.setTextSize(16);
        waveform.setTextSize(16);

    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        items.setStatus(1);
        List<Items> lis = itemsService.getItems(items);
        if (lis.size() > 0) {
            return lis.get(0);
        }
        return null;
    }

    private void permutations() {
        img.setVisibility(View.VISIBLE);
        no_data_img.setVisibility(View.GONE);
        mChart2.setVisibility(View.VISIBLE);
        mChart1.setVisibility(View.GONE);
        mChart3.setVisibility(View.GONE);
        mChart4.setVisibility(View.GONE);
        plan_break.setTextColor(Color.parseColor("#A6000000"));
        permutations.setTextColor(Color.parseColor("#FF007AFF"));
        waveform.setTextColor(Color.parseColor("#A6000000"));
        frequency_spectrum.setTextColor(Color.parseColor("#A6000000"));

        plan_break.setTextSize(16);
        permutations.setTextSize(18);
        waveform.setTextSize(16);
        waveform.setTextSize(16);
    }

    private void waveform() {
        img.setVisibility(View.VISIBLE);
        no_data_img.setVisibility(View.GONE);
        mChart3.setVisibility(View.VISIBLE);
        mChart1.setVisibility(View.GONE);
        mChart2.setVisibility(View.GONE);

        mChart4.setVisibility(View.GONE);
        plan_break.setTextColor(Color.parseColor("#A6000000"));
        permutations.setTextColor(Color.parseColor("#A6000000"));
        waveform.setTextColor(Color.parseColor("#FF007AFF"));
        frequency_spectrum.setTextColor(Color.parseColor("#A6000000"));
        plan_break.setTextSize(16);
        permutations.setTextSize(16);
        waveform.setTextSize(18);
        frequency_spectrum.setTextSize(16);

    }

    private void frequencySpectrum() {
        mChart4.setVisibility(View.VISIBLE);
        no_data_img.setVisibility(View.GONE);
        img.setVisibility(View.VISIBLE);
        mChart1.setVisibility(View.GONE);
        mChart2.setVisibility(View.GONE);
        mChart3.setVisibility(View.GONE);

        plan_break.setTextColor(Color.parseColor("#A6000000"));
        permutations.setTextColor(Color.parseColor("#A6000000"));
        waveform.setTextColor(Color.parseColor("#A6000000"));
        frequency_spectrum.setTextColor(Color.parseColor("#FF007AFF"));
        plan_break.setTextSize(16);
        permutations.setTextSize(16);
        waveform.setTextSize(16);
        frequency_spectrum.setTextSize(18);

    }

    private void savebitmap(Bitmap bitmap, String name) {

        //创建文件，因为不存在2级目录，所以不用判断exist，要保存png，这里后缀就是png，要保存jpg，后缀就用jpg
        File file = new File(ContextVariable.DOWN_NAME + "/img/" + fileName + "_" + name + ".png");
        File downloadFile = new File(ContextVariable.IMG_DOWN_NAME);
        try {
            if (!downloadFile.exists()) {
                downloadFile.mkdir();
            }
            //文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            //压缩图片，如果要保存png，就用Bitmap.CompressFormat.PNG，要保存jpg就用Bitmap.CompressFormat.JPEG,质量是100%，表示不压缩
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            //写入，这里会卡顿，因为图片较大
            fileOutputStream.flush();
            //记得要关闭写入流
            fileOutputStream.close();
            //成功的提示，写入成功后，请在对应目录中找保存的图片
            //System.out.println("写入成功！目录" + Environment.getExternalStorageDirectory() + "/" + name + ".png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            //失败的提示
            System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/" + name + ".png");
        } catch (IOException e) {
            e.printStackTrace();
            //失败的提示
            System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/" + name + ".png");
        }

    }

    public synchronized void saveCvs() {
        try {
            if(null == queueMsg || queueMsg.QueueEmpty()){
                return;
            }
            Log.d("saveCvs", "---------------saveCvs----------------");
            String fileNames = fileName + "_" + permutationMode + "_" + saveTime + ".cvs";
            //String fileNames = "qqqqqqqqqqqqqqq.cvs";
            saveCvsFileName = fileNames;
            Boolean bl = FileDownUtil.MakeFile(fileName);
            if (FileDownUtil.readFileSize(fileNames) == 1) {
                FileDownUtil.GZIPFile(fileName, fileNames);
            }
            int len = queueMsg.QueueLength() / 12;
            String[] vel = new String[len];
            String[] velLisnew = new String[len];
            //int ii = 0;
            for (int i = 0; i < len; i++) {
                //ii+=1;
                StringBuffer val = new StringBuffer();
                for (int j = 0; j < 12; j++) {
                    if(!queueMsg.QueueEmpty()){
                        val.append(queueMsg.deQueue().toString());
                    }

                }
                //vel[i] = val.toString().replace(";", "");
                vel[i] = val.toString().replace(";", "\n");
//            String[] velLis = vel[i].toString().split(",");
//            for (int j = 0; j < velLis.length; j++) {
//                if(j==3 || j==4 || j==5 || j==6){
//                    velLis[j] = boxLatLon.get(Integer.parseInt(velLis[j]) - 1);
//                }
//            }
//            String velStr = String.join(",", velLis);
//            velLisnew[i] = velStr+"\n";
            }

            Map<String, Integer> map = FileDownUtil.appendToFile( vel, fileNames, cvs_line, csv_line_count);
            cvs_line = map.get("cvs_line");
            csv_line_count = map.get("csv_line_count");
            System.out.println("====csv_line_count==== " + csv_line_count);
            System.out.println("====count_line=  " + count_line);
            if (csv_line_count.equals(count_line)) {
                String destinationPath = DOWN_NAME + fileName.replace(".cvs", "") + "/" + saveCvsFileName;
                String destinationPathNoDownName = fileName.replace(".cvs", "") + "/" + saveCvsFileName;
                String fileNameNew = fileName.replace(".cvs", "") + "/" + saveCvsFileName;
                Boolean boo = FileDownUtil.moveFile(DOWN_NAME + saveCvsFileName, destinationPath, myContext);
                try {
                    Thread.sleep(2000);
                    //将剩下的未压缩csv文件压缩、删除
                    FileDownUtil.GZIPFile(fileName, destinationPathNoDownName);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //pauseThread();
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    /**
     * 1装置系数计算
     * 2电阻率计算
     */
    private BigDecimal getResistivity(int A, int B, int M, int N, BigDecimal rxV, BigDecimal txI) {
        // 直接使用 Math.PI 获取圆周率
        double piValue = Math.PI;
//        Integer AM = Math.abs(M - A);
//        Integer BM = Math.abs(M - B);
//        Integer AN = Math.abs(N - A);
//        Integer BN = Math.abs(N - B);
//        if(kVal == 0){
        kVal = getKVal(A, B, M, N);
        //}


        BigDecimal resistivityVal = kVal.multiply(rxV.divide(txI, 5, RoundingMode.HALF_UP)).setScale(5, RoundingMode.HALF_UP);
        return resistivityVal;
    }

    //保存数据到CVS文件
//    public synchronized void saveRmsCvs() {
//        String fileNames = "RMS_" + fileName + "_" + permutationMode + "_" + saveTime + ".csv";
//        String[] rowVal = null;
//        Integer cvs_line_count = 0;
//        if (dtypelen0 == 1) {
//            rowVal = ContextVariable.vol_rms_ele.split("");
//            cvs_line_count = FileDownUtil.saveFileNew(myContext, rowVal, fileNames, cvs_line, fileName);
//            rowVal = dataNormaliza(convertTo2DArray(VIRO));
//            cvs_line_count = FileDownUtil.saveFileNew(myContext, rowVal, fileNames, cvs_line, fileName);
//        } else {
//            rowVal = dataNormaliza(convertTo2DArray(VIRO));
//            cvs_line_count = FileDownUtil.saveFileNew(myContext, rowVal, fileNames, cvs_line, fileName);
//        }
//        //msAllData.add(pyObject);
//        cvs_line = cvs_line_count;
//    }

    /**
     * 将List<List<BigDecimal>>转换为BigDecimal[][]
     */
    public static BigDecimal[][] convertTo2DArray(ArrayList<ArrayList<BigDecimal>> list) {
        if (list == null) {
            return null;
        }

        // 创建二维数组，行数为list的大小
        BigDecimal[][] array = new BigDecimal[list.size()][];

        // 遍历list的每个元素（即每行）
        for (int i = 0; i < list.size(); i++) {
            List<BigDecimal> row = list.get(i);
            if (row != null) {
                // 将每行转换为数组
                //array[i] = new String[]{Arrays.toString(row.toArray(new BigDecimal[0]))};
//                array[i] = row.stream()
//                        .map(BigDecimal::toPlainString)
//                        .collect(Collectors.toList()).toArray(new String[0]);
                array[i] = row.toArray(new BigDecimal[0]);
                //System.out.println(array[i]);
            } else {
                // 如果行为null，则该行设为null
                array[i] = null;
            }
        }

        return array;
    }

    //    static int aaa=0;
//    public static void main(String[] args) {
//        byte[] by = new byte[3];
//        by[0] = 0;
//        by[1] = 32;
//        by[2] = 0;
//        System.out.println("----------------------"+new String(by));
//
////        Timer timer = new Timer();
////        timer.schedule(new TimerTask() {
////            @Override
////            public void run() {
////                aaa+=1;
////                System.out.println("----timerbytecount------- ");
////                if (aaa == 5) {
////                    //Log.e("available1", "-------------available1 ==0 -----------");
////                    timer.cancel();
////                }
////            }
////        }, 3000,1000);
//    }
    public static void main(String[] args) {

        byte[] bytes = new byte[]{(byte) 0xFF, 0x39, (byte) 0xC0, (byte) 0xFF, 0x29, (byte) 0xEC}; // ASCII 编码的 "Hello"
//        String str = new String(bytes, java.nio.charset.StandardCharsets.US_ASCII);
//        System.out.println(str); // 输出: Hello

        // 3. 转换为 ASCII 字符串
//        StringBuilder ascii = new StringBuilder();
//        for (byte b : bytes) {
//            ascii.append((char) b);
//        }
//
//        System.out.println(ascii); // 输出: Hello, World!

        // 使用 ByteBuffer 并指定字节序
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN); // 设置为小端序
        int value = buffer.getInt();

        System.out.print(value); // 输出: 0x12345678
    }
}